Here are the examples of the python api flask_sqlalchemy.SQLAlchemy taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
26 Examples
3
Source : app.py
with MIT License
from AdrianVollmer
with MIT License
from AdrianVollmer
def init_db(self):
try:
from flask_sqlalchemy import SQLAlchemy
from powerhub.sql import init_db
db = SQLAlchemy(self.flask_app)
init_db(db)
except ImportError as e:
log.error("You have unmet dependencies, "
"database will not be available")
log.exception(e)
db = None
self.db = db
def init_clipboard(self):
3
Source : run.py
with MIT License
from cs91chris
with MIT License
from cs91chris
def main():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'more_difficult_string'
app.config['FLASK_ADMIN_SWATCH'] = 'cosmo'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite+pysqlite:///examples/db.sqlite3'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
admin = Admin(app)
db = SQLAlchemy(app)
autocrud = AutoCrud(app, db)
for k, m in autocrud.models.items():
setattr(CustomAdminView, 'column_searchable_list', m.searchable())
admin.add_view(CustomAdminView(m, db.session))
app.run(debug=True)
if __name__ == '__main__':
3
Source : test_utils.py
with MIT License
from dwreeves
with MIT License
from dwreeves
def test_get_db_function(base_app):
# No db extension
with pytest.raises(SqlaExtensionNotFound):
with base_app.app_context():
get_db()
# This works perfectly fine.
db1 = SQLAlchemy(base_app)
with base_app.app_context():
db2 = get_db()
assert db1 is db2
# No app context
with pytest.raises(RuntimeError):
get_db()
def test_raise_err_if_disallowed_function(base_app):
3
Source : test_flask_sqlathanor.py
with MIT License
from insightindustry
with MIT License
from insightindustry
def test_initialize_flask_sqlathanor(flask_app, cls, fails):
db = SQLAlchemy(app = flask_app, model_class = cls)
if not fails:
db = initialize_flask_sqlathanor(db)
expected_result = not fails
assert hasattr(db.Model, 'to_json') is expected_result
relationship = db.relationship('test_relationship')
assert isinstance(relationship, RelationshipProperty) is expected_result
column = db.Column('test_column', Integer)
assert isinstance(column, Column) is expected_result
3
Source : _conftest.py
with MIT License
from jeancochrane
with MIT License
from jeancochrane
def _db(app):
'''
Provide the transactional fixtures with access to the database via a Flask-SQLAlchemy
database connection.
'''
db = SQLAlchemy(app=app)
return db
@pytest.fixture(scope='module')
3
Source : __init__.py
with MIT License
from liranmatcu
with MIT License
from liranmatcu
def create_app():
app = Flask(__name__)
app.config.from_object('settings')
db = SQLAlchemy()
db.init_app(app)
return app
# ck_table
class ck_table(db.Model):
3
Source : test_load.py
with MIT License
from maarten-dp
with MIT License
from maarten-dp
def test_it_can_load_from_flask_sqlalchemy():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///:memory:"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
fa = FlaskFastAlchemy(db)
with fa:
fa.load(os.path.join(DATA_DIR, 'instances.yaml'))
fa.load(os.path.join(DATA_DIR, 'instances.yaml'))
assert len(fa.AntCollection.query.all()) == 4
assert len(fa.SandwichFormicarium.query.all()) == 3
assert len(fa.FreeStandingFormicarium.query.all()) == 2
assert len(fa.AntColony.query.all()) == 6
def test_it_can_export_models_to_python_code(temp_file):
3
Source : __init__.py
with Apache License 2.0
from mercadolibre
with Apache License 2.0
from mercadolibre
def create_app():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI #Connectar con proxySQL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # Setting this paramete due to a SQLAlchemy Warning, can be removed of future versions of the package.
os.environ['AWS_ACCESS_KEY_ID'] = AWS_ACCESS_KEY_ID
os.environ['AWS_SECRET_ACCESS_KEY'] = AWS_SECRET_ACCESS_KEY
db = SQLAlchemy(app)
db.init_app(app)
app.url_map.strict_slashes = False
for url, scopes, blueprint in ACTIVE_ENDPOINTS:
if os.environ.get('SCOPE') in scopes or not scopes:
app.register_blueprint(blueprint, url_prefix=url)
return app
3
Source : db.py
with MIT License
from osmangoninahid
with MIT License
from osmangoninahid
def connect_to_db(app):
"""Connect the database to Flask app."""
db_uri = "postgres://{0}:{1}@{2}:{3}/{4}".format(
DB_USER,
DB_PASSWORD,
DB_HOST,
DB_PORT,
DB_NAME)
db = SQLAlchemy()
# Configure to use PostgreSQL database
app.config['SQLALCHEMY_DATABASE_URI'] = db_uri
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.app = app
db.init_app(app)
0
Source : users.py
with GNU General Public License v3.0
from cellgeni
with GNU General Public License v3.0
from cellgeni
def create_app():
""" Flask application factory """
# Create Flask app load app.config
app = Flask(__name__)
app.config.from_object(__name__ + '.ConfigClass')
# Initialize Flask-BabelEx
babel = Babel(app)
# Initialize Flask-SQLAlchemy
db = SQLAlchemy(app)
# Define the User data-model.
# NB: Make sure to add flask_user UserMixin !!!
class User(db.Model, UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
active = db.Column('is_active', db.Boolean(), nullable=False, server_default='1')
# User authentication information. The collation='NOCASE' is required
# to search case insensitively when USER_IFIND_MODE is 'nocase_collation'.
email = db.Column(db.String(255, collation='NOCASE'), nullable=False, unique=True)
email_confirmed_at = db.Column(db.DateTime())
password = db.Column(db.String(255), nullable=False, server_default='')
# User information
first_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')
last_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')
# Define the relationship to Role via UserRoles
roles = db.relationship('Role', secondary='user_roles')
# Define the Role data-model
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(50), unique=True)
# Define the UserRoles association table
class UserRoles(db.Model):
__tablename__ = 'user_roles'
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('users.id', ondelete='CASCADE'))
role_id = db.Column(db.Integer(), db.ForeignKey('roles.id', ondelete='CASCADE'))
# Setup Flask-User and specify the User data-model
user_manager = UserManager(app, db, User)
# Create all database tables
db.create_all()
# Create '[email protected]' user with no roles
if not User.query.filter(User.email == '[email protected]').first():
user = User(
email='[email protected]',
email_confirmed_at=datetime.datetime.utcnow(),
password=user_manager.hash_password('Password1'),
)
db.session.add(user)
db.session.commit()
# Create '[email protected]' user with 'Admin' and 'Agent' roles
if not User.query.filter(User.email == '[email protected]').first():
user = User(
email='[email protected]',
email_confirmed_at=datetime.datetime.utcnow(),
password=user_manager.hash_password('Password1'),
)
user.roles.append(Role(name='Admin'))
user.roles.append(Role(name='Agent'))
db.session.add(user)
db.session.commit()
# The Home page is accessible to anyone
@app.route('/')
def home_page():
return render_template_string("""
{% extends "flask_user_layout.html" %}
{% block content %}
< h2>{%trans%}Home page{%endtrans%} < /h2>
< p> < a href={{ url_for('user.register') }}>{%trans%}Register{%endtrans%} < /a> < /p>
< p> < a href={{ url_for('user.login') }}>{%trans%}Sign in{%endtrans%} < /a> < /p>
< p> < a href={{ url_for('home_page') }}>{%trans%}Home Page{%endtrans%} < /a> (accessible to anyone) < /p>
< p> < a href={{ url_for('member_page') }}>{%trans%}Member Page{%endtrans%} < /a> (login_required: [email protected] / Password1) < /p>
< p> < a href={{ url_for('admin_page') }}>{%trans%}Admin Page{%endtrans%} < /a> (role_required: [email protected] / Password1') < /p>
< p> < a href={{ url_for('user.logout') }}>{%trans%}Sign out{%endtrans%} < /a> < /p>
{% endblock %}
""")
# The Members page is only accessible to authenticated users
@app.route('/members')
@login_required # Use of @login_required decorator
def member_page():
return render_template_string("""
{% extends "flask_user_layout.html" %}
{% block content %}
< h2>{%trans%}Members page{%endtrans%} < /h2>
< p> < a href={{ url_for('user.register') }}>{%trans%}Register{%endtrans%} < /a> < /p>
< p> < a href={{ url_for('user.login') }}>{%trans%}Sign in{%endtrans%} < /a> < /p>
< p> < a href={{ url_for('home_page') }}>{%trans%}Home Page{%endtrans%} < /a> (accessible to anyone) < /p>
< p> < a href={{ url_for('member_page') }}>{%trans%}Member Page{%endtrans%} < /a> (login_required: [email protected] / Password1) < /p>
< p> < a href={{ url_for('admin_page') }}>{%trans%}Admin Page{%endtrans%} < /a> (role_required: [email protected] / Password1') < /p>
< p> < a href={{ url_for('user.logout') }}>{%trans%}Sign out{%endtrans%} < /a> < /p>
{% endblock %}
""")
# The Admin page requires an 'Admin' role.
@app.route('/admin')
@roles_required('Admin') # Use of @roles_required decorator
def admin_page():
return render_template_string("""
{% extends "flask_user_layout.html" %}
{% block content %}
< h2>{%trans%}Admin Page{%endtrans%} < /h2>
< p> < a href={{ url_for('user.register') }}>{%trans%}Register{%endtrans%} < /a> < /p>
< p> < a href={{ url_for('user.login') }}>{%trans%}Sign in{%endtrans%} < /a> < /p>
< p> < a href={{ url_for('home_page') }}>{%trans%}Home Page{%endtrans%} < /a> (accessible to anyone) < /p>
< p> < a href={{ url_for('member_page') }}>{%trans%}Member Page{%endtrans%} < /a> (login_required: [email protected] / Password1) < /p>
< p> < a href={{ url_for('admin_page') }}>{%trans%}Admin Page{%endtrans%} < /a> (role_required: [email protected] / Password1') < /p>
< p> < a href={{ url_for('user.logout') }}>{%trans%}Sign out{%endtrans%} < /a> < /p>
{% endblock %}
""")
return app
# Start development web server
if __name__ == '__main__':
0
Source : test_{{ cookiecutter.project_slug_no_hyphen }}.py
with Apache License 2.0
from cookiejar
with Apache License 2.0
from cookiejar
def create_test_app():
migrate = Migrate()
db = SQLAlchemy()
login = LoginManager()
login.login_view = 'auth.login'
login.login_message = 'Please log in to access this page.'
bootstrap = Bootstrap()
babel = Babel()
app = Flask(__name__)
app.config.from_object(Config)
migrate.init_app(app, db)
login.init_app(app)
bootstrap.init_app(app)
babel.init_app(app)
from {{cookiecutter.project_slug}}.errors import bp as errors_bp # noqa: E402
app.register_blueprint(errors_bp)
from {{cookiecutter.project_slug}}.auth import bp as auth_bp # noqa: E402
app.register_blueprint(auth_bp, url_prefix='/auth')
from {{cookiecutter.project_slug}}.main import bp as main_bp # noqa: E402
app.register_blueprint(main_bp)
return app
def test_redirect():
0
Source : run.py
with MIT License
from cs91chris
with MIT License
from cs91chris
def create_app(config=None):
"""
:param config:
:return:
"""
app = Flask(__name__)
app.config.update(config or {})
FlaskLogging(app)
db = SQLAlchemy(app)
builder = ResponseBuilder(app)
error = ErrorHandler(app, response=builder.on_accept())
autocrud = AutoCrud(app, db, builder=builder, error=error)
for m in autocrud.models.keys():
app.logger.info('Registered resource: {}'.format(m))
error.api_register(app)
return app
@click.command()
0
Source : test_executor.py
with MIT License
from dchevell
with MIT License
from dchevell
def test_sqlalchemy(default_app, caplog):
default_app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {'echo_pool': 'debug', 'echo': 'debug'}
default_app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
default_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
default_app.config['EXECUTOR_PUSH_APP_CONTEXT'] = True
default_app.config['EXECUTOR_MAX_WORKERS'] = 1
db = flask_sqlalchemy.SQLAlchemy(default_app)
def test_db():
return list(db.session.execute('select 1'))
executor = Executor(default_app)
with default_app.test_request_context():
for i in range(2):
with caplog.at_level('DEBUG'):
caplog.clear()
future = executor.submit(test_db)
concurrent.futures.wait([future])
future.result()
assert 'checked out from pool' in caplog.text
assert 'being returned to pool' in caplog.text
0
Source : test_cli_normal_app_config.py
with MIT License
from dwreeves
with MIT License
from dwreeves
def db() -> SQLAlchemy:
return SQLAlchemy()
@pytest.fixture
0
Source : test_utils.py
with MIT License
from dwreeves
with MIT License
from dwreeves
def test_resolve_init_db_callback_function(
base_app,
func: callable,
app_is_arg: bool,
db_is_arg: bool,
capsys
):
assert app_is_arg == bool("app" in inspect.signature(func).parameters)
assert db_is_arg == bool("db" in inspect.signature(func).parameters)
new_func = resolve_init_db_callback(func)
assert "app" in inspect.signature(new_func).parameters
assert "db" in inspect.signature(new_func).parameters
db = SQLAlchemy(base_app)
assert capsys.readouterr().out == ""
with base_app.app_context():
new_func(app=base_app, db=db) # noqa
assert capsys.readouterr().out == "I ran OK\n"
@pytest.mark.filterwarnings("ignore:.*SQLALCHEMY.*")
0
Source : app.py
with MIT License
from Ermlab
with MIT License
from Ermlab
def create_app(image_storage):
'''Function returning Flask app instance
'''
global bcrypt, database, jwt, app, dbc
app = FlaskAPI(__name__)
CORS(app, origins=white_list)
models_holder_instance = ModelsHolderClass(MODELS_DIR)
app_settings = os.getenv('APP_SETTINGS','db.config.DevelopmentConfig')
app.config.from_object(app_settings)
logging.info("Using {} settings.".format(app_settings))
bcrypt = Bcrypt(app)
try:
database = SQLAlchemy(app)
except Exception:
logging.critical("Couldn't connect to DB!")
from db.dbConnection import DbConnectionClass
dbc = DbConnectionClass(database, app.config)
jwt = JWT(app, dbc.authenticate, dbc.identity)
@app.route('/')
def slash():
return redirect(url_for('root'))
@app.route('/v2/', methods=['GET'])
def root():
'''Function responding to request to "/v2/" route.
Returns a list of possible routes.
'''
text = {
'available_routes': [
"api.mlapi.io/v2/token - Check current token balance status [POST]",
"api.mlapi.io/v2/test1 - Car recognition NN[GET, POST]",
]
}
return text
@app.route('/v2/token', methods=['GET'])
@jwt_required()
def token():
'''Retrieve description of route or amount of uses left on token
'''
return {
"uses_left": str(dbc.get_users_available_uses(current_identity['user_id']))
}
@app.route('/v2/user', methods=['POST', 'PATCH', 'DELETE'])
@set_parsers(JSONParser)
@jwt_required()
def user():
'''Manage users.
'''
#################################
#### METHODS FOR ADMIN USERS ONLY
if request.method == 'POST':
req = request.data
logging.debug(req)
uses = req['uses'] if 'uses' in req else 100
isa = req['is_admin'] if "is_admin" in req else False
if 'email' not in req:
return {
'error' : "No email given"
}, status.HTTP_400_BAD_REQUEST
return create_user(dbc, req['email'], uses, isa)
elif request.method == 'DELETE':
id = request.user_id
return delete_user(id)
#### METHODS FOR ADMIN USERS ONLY
#################################
elif request.method == 'GET':
pass
elif request.method == 'PUT':
pass
## Needed for unathorized pre-requests
@app.route('/v2/test1', methods=['OPTIONS'])
def test1_opt():
return ""
@app.route('/v2/test1', methods=['GET', 'POST'])
@jwt_required()
@set_parsers(JSONParser, JpegImageParser, PngImageParser, MultiPartParser)
@reduce_uses
def test1(errors=None):
'''Responds with predictions on the sent image on POST. Returns description on GET request.
Accepted formats: image/jpeg, image/png, application/json with an image in Base64 format.
'''
if errors:
return {"result":errors_handler(errors)}
model_name = 'test1'
logging.debug("REQUEST: {}".format(repr(request)))
if request.method == 'GET':
return {
"description" : "Make an authenticated POST request for predicting the image. POST binary file with proper header or { 'image' : 'BASE64 image' }",
"accepted_content_type" : [
"image/jpeg",
"image/png",
"application/json"
]
}
elif request.method == 'POST':
# logging.debug("Got files from client: >>> {} < < < ".format(request.files))
if request.files:
val = request.files['file']
path = image_storage.save(val, request.headers['Content-Type'])
response = {
"result" : models_holder_instance.sendRequest(model_name, path)
}
save_request(
response = str(response['result']),
data_type = "I",
data = path)
return response
elif request.data:
path = image_storage.save(request.data, request.headers['Content-Type'])
response = {
"result" : models_holder_instance.sendRequest(model_name, path)
}
save_request(
response = str(response['result']),
data_type = "I",
data = path)
return response
else:
return {
"result":"You provided no data"
}
return app, bcrypt, database, image_storage, jwt
def get_app():
0
Source : run.py
with MIT License
from luissilva1044894
with MIT License
from luissilva1044894
def create_app():
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
def get_config(x=None):
return {
'development': 'config.DevelopementConfig',
'dev': 'config.DevelopementConfig',
'testing': 'config.TestingConfig',
'default': 'config.ProductionConfig',
'production': 'config.ProductionConfig',
'prod': 'config.ProductionConfig'
}.get(str(x).lower(), 'config.ProductionConfig')
app = Flask(__name__.split('.')[0], static_folder='static', template_folder='templates', static_url_path='', instance_relative_config=True)
app.config.from_object(get_config(get_env('FLASK_ENV', default='dev' if os.sys.platform == 'win32' else 'prod')))
app.config.from_pyfile('config.cfg', silent=True)
print(app.secret_key)
@app.teardown_request
def teardown_request_func(error=None):
"""
This function will run after a request, regardless if an exception occurs or not.
It's a good place to do some cleanup, such as closing any database connections.
If an exception is raised, it will be passed to the function.
You should so everything in your power to ensure this function does not fail, so
liberal use of try/except blocks is recommended.
"""
if error:
# Log the error
app.logger.error(error)
@app.route('/index', methods=['GET'])
@app.route('/index.html', methods=['GET'])
@app.route('/', methods=['GET'])
def _root(error=None):
from flask import redirect, url_for
return redirect(url_for('api.root'))
@app.after_request
def jsonify_request(response):
"""JSONify the response. https://github.com/Fuyukai/OWAPI/blob/master/owapi/app.py#L208"""
if response.headers.get('Content-Type', '').lower() == app.config['JSONIFY_MIMETYPE'].lower():
from flask import request
import json
if request.args.get('format', 'json') in ['json_pretty', 'pretty'] or app.config['JSONIFY_PRETTYPRINT_REGULAR']:
from datetime import datetime, timedelta, timezone
from email.utils import format_datetime
response.set_data(json.dumps(response.get_json(), sort_keys=app.config['JSON_SORT_KEYS'], ensure_ascii=app.config['JSON_AS_ASCII'], indent=4, separators=(',', ': ')))
response.headers['Cache-Control'] = 'public, max-age=300'
response.headers['Expires'] = format_datetime((datetime.utcnow() + timedelta(seconds=300)).replace(tzinfo=timezone.utc), usegmt=True)
return response
def get_http_exception_handler(app):
"""Overrides the default http exception handler to return JSON."""
from functools import wraps
handle_http_exception = app.handle_http_exception
@wraps(handle_http_exception)
def ret_val(error):
"""Generic exception handler for general exceptions"""
if not app.env.lower().startswith('dev') and error.code == 404:
from flask import redirect, url_for
return redirect(url_for('api.root'))
#from werkzeug.exceptions import HTTPException
#if isinstance(e, HTTPException) and (500 < = e.code < 600):
# return error
if not hasattr(error, 'code'):# or isinstance(error, HTTPException):
error.code = 500
from werkzeug.exceptions import default_exceptions
if error.code in default_exceptions:
# Returning directly as below results in missing Location header
# on 301 errors which is useful for this test as it will fail to redirect.
def get_http_error_code(error_code=500):
return {
301: u'Moved Permanently', 302: u'Found', 303: u'See Other', 304: u'Not Modified',
400: u'Bad request', 401: u'Unauthorized', 403: u'Forbidden', 404: u'Resource not found', 405: u'Method not allowed',
408: u'Request Timeout', 409: u'Conflict', 410: u'Gone', 418: u'I am a teapot', 429: u'Too many requests',
500: u'Internal server error', 501: u'Not Implemented', 502: u'Bad Gateway', 503: u'Service unavailable', 504: u'Gateway Timeout'
}.get(error_code, 500)
from flask import jsonify
if not hasattr(error, 'original_exception'):
error.original_exception = error or None
return jsonify(code=get_http_error_code(error.code), description=error.description, message=str(error.original_exception), error=error.code), error.code
return handle_http_exception(error)
return ret_val
# Override the HTTP exception handler.
app.config['TRAP_HTTP_EXCEPTIONS'] = True
#TRAP_BAD_REQUEST_ERRORS = PROPAGATE_EXCEPTIONS = True
app.handle_http_exception = get_http_exception_handler(app)
from werkzeug.exceptions import default_exceptions #werkzeug import HTTP_STATUS_CODES
for exc in default_exceptions: #exc in HTTPException.__subclasses__() | exc in HTTP_STATUS_CODES
app.register_error_handler(exc, get_http_exception_handler(app))
app.register_error_handler(Exception, get_http_exception_handler(app))
#if request.path.startswith('/api/'): return jsonify_error(ex)
#else: return ex
import logging
handler = logging.FileHandler('static/flask.log')#RotatingFileHandler('flask.log', maxBytes=1024 * 1024 * 100, backupCount=3)
handler.setLevel(logging.DEBUG if app.config['DEBUG'] else logging.INFO)
handler.setFormatter(logging.Formatter('[%(levelname)s|%(filename)s:%(lineno)s] ' '%(asctime)s %(message)s \r\n'))
app.logger.addHandler(handler)
# Blueprints
from app import register
register(app)
return app, SQLAlchemy(app)
app, db = create_app()
0
Source : conftest.py
with MIT License
from shawalli
with MIT License
from shawalli
def db(app):
"""Empty test database and create database controller.
Parameters
----------
app: Flask
Test Flask application to which the extension should be registered.
Returns
-------
flask_sqlalchemy.SQLAlchemy
Flask-SQLAlchemy database controller
"""
db_ = SQLAlchemy()
db_.init_app(app)
# Ensure database is empty
meta = MetaData(db_.engine)
meta.reflect()
meta.drop_all()
return db_
def patched_visit_create_schema(self_, create):
0
Source : conftest.py
with MIT License
from siddhantgoel
with MIT License
from siddhantgoel
def db(app):
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
return SQLAlchemy(app)
0
Source : app.py
with MIT License
from tiagoluizrs
with MIT License
from tiagoluizrs
def create_app(config_name):
app = Flask(__name__, template_folder='templates')
login_manager = LoginManager()
login_manager.init_app(app)
app.secret_key = config.SECRET
app.config.from_object(app_config[config_name])
app.config.from_pyfile('config.py')
app.config['SQLALCHEMY_DATABASE_URI'] = config.SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['FLASK_ADMIN_SWATCH'] = 'paper'
db = SQLAlchemy(config.APP)
migrate = Migrate(app, db)
start_views(app,db)
Bootstrap(app)
db.init_app(app)
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
return response
def auth_token_required(f):
@wraps(f)
def verify_token(*args, **kwargs):
user = UserController()
try:
result = user.verify_auth_token(request.headers['access_token'])
if result['status'] == 200:
return f(*args, **kwargs)
else:
abort(result['status'], result['message'])
except KeyError as e:
abort(401, 'Você precisa enviar um token de acesso')
return verify_token
@app.route('/')
def index():
return 'Meu primeiro run'
@app.route('/login/')
def login():
return render_template('login.html', data={'status': 200, 'msg': None, 'type': None})
@app.route('/login/', methods=['POST'])
def login_post():
user = UserController()
email = request.form['email']
password = request.form['password']
result = user.login(email, password)
if result:
if result.role == 4:
return render_template('login.html', data={'status': 401, 'msg': 'Seu usuário não tem permissão para acessar o admin', 'type':2})
else:
login_user(result)
return redirect('/admin')
else:
return render_template('login.html', data={'status': 401, 'msg': 'Dados de usuário incorretos', 'type': 1})
@app.route('/recovery-password/')
def recovery_password():
# Capítulo 11
return render_template('recovery.html', data={'status': 200, 'msg': None, 'type': None})
@app.route('/recovery-password/', methods=['POST'])
def send_recovery_password():
user = UserController()
result = user.recovery(request.form['email'])
# Capítulo 11 - Alterar parâmetros
if result['status_code'] == 200 or result['status_code'] == 202:
return render_template('recovery.html', data={'status': result['status_code'], 'msg': 'Você receberá um e-mail em sua caixa para alteração de senha.', 'type': 3})
else:
return render_template('recovery.html', data={'status': result['status_code'], 'msg': result['body'], 'type': 1})
@app.route('/new-password/ < recovery_code>')
def new_password(recovery_code):
user = UserController()
result = user.verify_auth_token(recovery_code)
if result['status'] == 200:
res = user.get_user_by_recovery(str(recovery_code))
if res is not None:
return render_template('new_password.html', data={'status': result['status'], 'msg': None, 'type': None, 'user_id': res.id})
else:
return render_template('recovery.html', data={'status': 400, 'msg': 'Erro ao tentar acessar os dados do usuário. Tente novamente mais tarde.', 'type': 1})
else:
return render_template('recovery.html', data={'status': result['status'], 'msg': 'Token expirado ou inválido, solicite novamente a alteração de senha', 'type': 1})
@app.route('/new-password/', methods=['POST'])
def send_new_password():
user = UserController()
user_id = request.form['user_id']
password = request.form['password']
result = user.new_password(user_id, password)
if result:
return render_template('login.html', data={'status': 200, 'msg': 'Senha alterada com sucesso!', 'type': 3, 'user_id': user_id})
else:
return render_template('new_password.html', data={'status': 401, 'msg': 'Erro ao alterar senha.', 'type': 1, 'user_id': user_id})
@app.route('/products/', methods=['GET'])
@app.route('/products/ < limit>', methods=['GET'])
@auth_token_required
def get_products(limit=None):
header = {
'access_token': request.headers['access_token'],
"token_type": "JWT"
}
product = ProductController()
response = product.get_products(limit=limit)
return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), response['status'], header
@app.route('/product/ < product_id>', methods=['GET'])
@auth_token_required
def get_product(product_id):
header = {
'access_token': request.headers['access_token'],
"token_type": "JWT"
}
product = ProductController()
response = product.get_product_by_id(product_id = product_id)
return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), response['status'], header
@app.route('/user/ < user_id>', methods=['GET'])
@auth_token_required
def get_user_profile(user_id):
header = {
'access_token': request.headers['access_token'],
"token_type": "JWT"
}
user = UserController()
response = user.get_user_by_id(user_id=user_id)
return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), response['status'], header
@app.route('/login_api/', methods=['POST'])
def login_api():
header = {}
user = UserController()
email = request.json['email']
password = request.json['password']
result = user.login(email, password)
code = 401
response = {"message": "Usuário não autorizado", "result": []}
if result:
if result.active:
result = {
'id': result.id,
'username': result.username,
'email': result.email,
'date_created': result.date_created,
'active': result.active
}
header = {
"access_token": user.generate_auth_token(result),
"token_type": "JWT"
}
code = 200
response["message"] = "Login realizado com sucesso"
response["result"] = result
return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), code, header
@app.route('/logout')
def logout_send():
logout_user()
return render_template('login.html', data={'status': 200, 'msg': 'Usuário deslogado com sucesso!', 'type':3})
@login_manager.user_loader
def load_user(user_id):
user = UserController()
return user.get_admin_login(user_id)
return app
0
Source : agent.py
with Apache License 2.0
from UCY-LINC-LAB
with Apache License 2.0
from UCY-LINC-LAB
def __init__(self, args, app):
"""
It instantiates the agent and starts the API server
:param args:
:param app:
"""
db_path = os.getcwd() + '/agent_database.db'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + db_path
Agent.db = SQLAlchemy(app)
if os.path.exists(db_path): os.remove(db_path)
os.mknod(db_path)
app.config['UPLOAD_FOLDER'] = "/current_agent/"
os.environ['UPLOAD_FOLDER'] = "/current_agent/"
if not os.path.exists(os.getcwd() + app.config['UPLOAD_FOLDER']):
os.mkdir(os.getcwd() + app.config['UPLOAD_FOLDER'])
connector = get_connector()
app.config['CONNECTOR'] = connector
node_labels = {}
if 'LABELS' in os.environ:
node_labels = {i.split(":")[0]: i.split(":")[1]
for i in os.environ['LABELS'].split(",") if len(i.split(":")) == 2}
node_labels.update(HostInfo.get_all_properties())
connector.inject_labels(node_labels, HOST_IP=os.environ['HOST_IP'] if 'HOST_IP' in os.environ else None)
from utils.monitoring import MetricCollector
from agent.views import MonitoringAPI, ActionsAPI, TopologyAPI, DistributionAPI, SnifferAPI
# Add the api routes
app.add_url_rule('/topology/', view_func=TopologyAPI.as_view('Topology'))
app.add_url_rule('/monitorings/', view_func=MonitoringAPI.as_view('Monitoring'))
app.add_url_rule('/actions/', view_func=ActionsAPI.as_view('Action'))
app.add_url_rule('/packets/', view_func=SnifferAPI.as_view('Packet'))
app.add_url_rule('/generate-network-distribution/ < string:name>/',
view_func=DistributionAPI.as_view('NetworkDistribution'))
# The thread that runs the monitoring agent
metricController = MetricCollector()
metricControllerTask = AsyncTask(metricController, 'start_monitoring', [args.agent_ip, connector, 5])
metricControllerTask.start()
# The thread that inspect containers and apply network QoS
networkController = NetworkController(connector)
networkControllerTask = AsyncTask(networkController, 'listen', [])
networkControllerTask.start()
self.app = app
self.args = args
0
Source : controller.py
with Apache License 2.0
from UCY-LINC-LAB
with Apache License 2.0
from UCY-LINC-LAB
def __init__(self, args, app):
"""
It instantiates the Controller server
:param args:
:param app:
"""
db_path = os.getcwd() + '/master_database.db'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + db_path
self.args = args
Controller.db = SQLAlchemy(app)
if os.path.exists(db_path): os.remove(db_path)
os.mknod(db_path)
app.config['UPLOAD_FOLDER'] = "/current_infrastructure/"
os.environ['UPLOAD_FOLDER'] = "/current_infrastructure/"
from controller.views import TopologyAPI, \
MonitoringAPI, \
ActionsAPI, \
ControlAPI, \
AnnotationAPI, \
DistributionAPI, \
SnifferAPI
# Introduce the routes of the API
app.add_url_rule('/topology/', view_func=TopologyAPI.as_view('Topology'))
app.add_url_rule('/monitorings/', view_func=MonitoringAPI.as_view('Monitoring'))
app.add_url_rule('/packets/', view_func=SnifferAPI.as_view('Packets'))
app.add_url_rule('/annotations/', view_func=AnnotationAPI.as_view('Annotations'))
app.add_url_rule('/actions/ < string:action_type>/', view_func=ActionsAPI.as_view('Action'))
app.add_url_rule('/control/ < string:service>/', view_func=ControlAPI.as_view('control'))
app.add_url_rule('/generate-network-distribution/ < string:name>/',
view_func=DistributionAPI.as_view('NetworkDistribution'))
# from .models import Status
# Status.update_config(self.initiate_swarm_manager(), "swarm-ca")
# app.run(debug=False, host='0.0.0.0')
self.app = app
0
Source : server.py
with GNU General Public License v3.0
from uysalemre
with GNU General Public License v3.0
from uysalemre
def create_app():
app = Flask(__name__)
app.config.from_object('settings')
app.register_blueprint(website)
app.secret_key = app.config.get('secret_key', 'secret')
app.sender = app.config.get('MAIL_USERNAME')
app.mail = Mail(app)
app.db = SQLAlchemy(app)
path = op.join(op.dirname(__file__), 'static')
app.admin = Admin(app, name="Casting Agency", template_mode='bootstrap3', index_view=MyAdminIndexView())
app.admin.add_view(AdminView(Categories, app.db.session))
app.admin.add_view(AdminView(User, app.db.session, category='User Ops'))
app.admin.add_view(AdminView(Role, app.db.session, category='User Ops'))
app.admin.add_view(AdminView(Agency, app.db.session, category='App Manager'))
app.admin.add_view(AdminView(NormalContact, app.db.session, category='App Manager'))
app.admin.add_view(AdminView(Setup, app.db.session, category='App Manager'))
app.admin.add_view(AdminView(StaticNav, app.db.session, category='App Manager'))
app.admin.add_view(AdminView(Actors, app.db.session, category='Actor Ops'))
app.admin.add_view(AdminView(ActorBody, app.db.session, category='Actor Ops'))
app.admin.add_view(AdminView(ActorSoul, app.db.session, category='Actor Ops'))
app.admin.add_view(AdminView(Photos, app.db.session, category='Actor Ops'))
app.admin.add_view(AdminView(TempActors, app.db.session, category='Coming Applies'))
app.admin.add_view(AdminView(TempActorBody, app.db.session, category='Coming Applies'))
app.admin.add_view(AdminView(TempActorSoul, app.db.session, category='Coming Applies'))
app.admin.add_view(AdminView(TempPhotos, app.db.session, category='Coming Applies'))
app.admin.add_view(MyFileView(path, '/static/', name='Static Files'))
app.permanent_session_lifetime = timedelta(hours=10)
app.user_datastore = SQLAlchemyUserDatastore(app.db, User, RolesUsers)
app.security = Security(app, app.user_datastore)
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
return app
def main():
0
Source : __init__.py
with Apache License 2.0
from verdan
with Apache License 2.0
from verdan
def __init__(self, *args, **kwargs):
super(FlaskOIDC, self).__init__(*args, **kwargs)
self.db = SQLAlchemy(self)
_provider = self.config.get("OIDC_PROVIDER").lower()
if _provider not in _CONFIGS.keys():
LOGGER.info(
f"""
[flaskoidc Notice] I have not verified the OIDC Provider that you have
selected i.e., "{_provider}" with this package yet.
If you encounter any issue while using this library with "{_provider}",
please do not hesitate to create an issue on Github. (https://github.com/verdan/flaskoidc)
"""
)
with self.app_context():
from flaskoidc.models import OAuth2Token
self.db.create_all()
oauth = OAuth(self, fetch_token=self._fetch_token, update_token=self._update_token)
self.auth_client = oauth.register(
name=_provider,
server_metadata_url=self.config.get("CONFIG_URL"),
client_kwargs={
"scope": self.config.get("OIDC_SCOPES"),
},
**_CONFIGS.get(_provider) if _CONFIGS.get(_provider) else {},
)
# Register the before request function that will make sure each
# request is authenticated before processing
self.before_request(self._before_request)
def unauthorized_redirect(err):
LOGGER.info("Calling the 401 Error Handler. 'unauthorized_redirect'")
return redirect(url_for("logout", _external=True))
self.register_error_handler(401, unauthorized_redirect)
@self.route("/login")
def login():
redirect_uri = url_for("auth", _external=True, _scheme=self.config.get("SCHEME"))
return self.auth_client.authorize_redirect(redirect_uri)
@self.route(self.config.get("REDIRECT_URI"))
def auth():
_db_keys = [
"access_token",
"expires_in",
"scope",
"token_type",
"refresh_token",
"expires_at",
]
try:
token = self.auth_client.authorize_access_token()
user = self.auth_client.parse_id_token(token)
user_id = user.get(self.config.get("USER_ID_FIELD"))
if not user_id:
raise BadRequest(
"Make sure to set the proper 'FLASK_OIDC_USER_ID_FIELD' env variable "
"to match with your OIDC Provider."
f"'{self.config.get('USER_ID_FIELD')}' is not present in the "
f"response from OIDC Provider. Available Keys are: ({', '.join(user.keys())})"
)
# Remove unnecessary keys from the token
db_token = {_key: token.get(_key) for _key in _db_keys}
OAuth2Token.save(name=_provider, user_id=user_id, **db_token)
session["user"] = user
session["user"]["__id"] = user_id
return redirect(self.config.get("OVERWRITE_REDIRECT_URI"))
except Exception as ex:
LOGGER.exception(ex)
raise ex
@self.route("/logout")
def logout():
# ToDo: Think of if we should delete the session entity or not
# if session.get("user"):
# OAuth2Token.delete(name=_provider, user_id=session["user"]["__id"])
session.pop("user", None)
return redirect(url_for("login"))
def make_config(self, instance_relative=False):
0
Source : sessions.py
with MIT License
from Vukan-Markovic
with MIT License
from Vukan-Markovic
def __init__(self, app, db, table, key_prefix, use_signer=False,
permanent=True):
if db is None:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
self.db = db
self.key_prefix = key_prefix
self.use_signer = use_signer
self.permanent = permanent
class Session(self.db.Model):
__tablename__ = table
id = self.db.Column(self.db.Integer, primary_key=True)
session_id = self.db.Column(self.db.String(255), unique=True)
data = self.db.Column(self.db.LargeBinary)
expiry = self.db.Column(self.db.DateTime)
def __init__(self, session_id, data, expiry):
self.session_id = session_id
self.data = data
self.expiry = expiry
def __repr__(self):
return ' < Session data %s>' % self.data
# self.db.create_all()
self.sql_session_model = Session
def open_session(self, app, request):
0
Source : sqlalchemy.py
with MIT License
from zemfrog
with MIT License
from zemfrog
def init_app(app: Flask):
db = SQLAlchemy()
db.init_app(app)