Esempio n. 1
0
def setup_database(app):
    register_tortoise(
        app,
        db_url=DB_URL,
        modules={"models": ["models"]},
        generate_schemas=False,
    )
Esempio n. 2
0
def create_app():
    app = Sanic(__name__)
    # Limiter(app, global_limits=['60 per minute'], key_func=get_remote_address)
    register_tortoise(app, generate_schemas=False, config=DBconfig)
    bcrypt = Bcrypt(app)
    # CORS(app, automatic_options=True)
    return app
Esempio n. 3
0
def create_app():
    app = Sanic(__name__)
    app: asyncio_redis.Pool
    app.blueprint(api)
    bcrypt = Bcrypt(app)
    register_tortoise(app, generate_schemas=False, config=postgres.config)
    CORS(app, automatic_options=True)
    # setup_cors(app)
    return app
Esempio n. 4
0
0R5v9JuxtcbXsFXua5KWoDojOvHkeP93F5eGSDu8iRo/4zhyHWGhZuMIuMARAOJ7tAyWxDTzoSILhC4+fF6WQJKiBIlLLGXFyJ9qgq2eN+Z/b9+k6PotQV9z
unmIN8vuCrtPBlVbOMrofGHG85zSDyDDDUXZoh7ko8tJ3nosCgYEAxAb/8E/fmEADxJZSFoqwlElXm6h7sfThrhjf12ENwBv7AvH8XsiNVQsIGnoVxeHQJ7U
0pROucD/iykf8I9+ou9ZBQyfoRJiOkzExeMWEyhmGyGmcNCZ1kKK/RZu6Bks/EoqnpVH9bUjjAwSXeFRZE3zfsAclQr3BYjqFjQzuSrsCgYEA7RhLBPwkPT6
C//wcqkJKgdfO/PhJtRPnG/sIYFf84vmiJZuMMgxLzfYSzO2wn/DU9d63LN7AVVoDurpXTbN4mUH5UKWmzJPThvMZFg9gzSmt9FLfI3lqRRzWw3FYiQMriKa
hlKh03tPVSVID73SuJ2Wx43u/0OstkGa/voQ34tECgYA+G2mjnerdtgp7kpTXh4GCueoD61GlhEyseD0TZDCTGUpiGIE5FpmQxDoBCYU0eOMWcZcIZj/yWIt
mQ4BjbU1slel/eXlhomQpxoBCH3J/Ba9qd+uBql29QZMQXtKFg/mryjprapq8sUcbgazr9u1x+zJz9w+bIbvPf3MoyVwGWQKBgQDXKMG9fV+/61imgsOZTyd
2ld8MnIWAeUGgk5e6P+niAOPGFSPue3FgGvLURiJtuu05dM9U9pQhtGVrCwHcT9Yixiwpnyw31DQp3uU91DhrtHyRIf3H/ywrWLwY4Z+TsktW6UPoe2cyGbN
1G1CHHo/vq8zPNkVWmhciIUeHR3YJbw==
-----END RSA PRIVATE KEY-----
"""
security_config.PUBLIC_SECRET = """
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAww3pEiUx6wMFawJNAHCI80Qj3eyrP6Yx3LNNluQZXMyZkd+6ugBN9e1hw7v2z2PwmJENhYrqbBHU
4vHCHEEZjdZIQRqwriFpeeoqMA1ecgwJz3fOuYo6WrUbS6pEyJ9vtjh5TaeZLzER+KIK2uvsjsQnFVt41hh3Xd+tR9p+QXT8aRep9hp4XLF87QlDVDrZIStf
Vn25+ZfSfKH+WYBUglZBmz/K6uW41mSRuuH3Pu/lnPgGvsxtT7KE8dkbyrI+Tyg0pniOYdxBxgpu06S6LTC8Zou0U0SGd6uOMUHT86H8uxbDTa8CNiGI251Q
MHlkstd6FFYu5lJQcuppOm79iQIDAQAB
-----END PUBLIC KEY-----
"""
security_config.SESSION_ENCODING_ALGORITHM = "RS256"
security_config.ALLOW_LOGIN_WITH_USERNAME = True
security_config.SESSION_EXPIRES_ON_CLIENT = True
security_config.AUTHENTICATION_SESSION_EXPIRATION = 0
register_tortoise(
    app,
    db_url=security_config.TEST_DATABASE_URL,
    modules={"models": ["sanic_security.models"]},
    generate_schemas=True,
)
if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8000, debug=True, workers=1)
Esempio n. 5
0
# routes
app.add_route(CustomerRouter.as_view(), '/customers', version=1)
# jwt
Initialize(
    app,
    configuration_class=configuration.JwtConfiguration,
    authenticate=authentication.authenticate,
    retrieve_user=authentication.retrieve_user
)
# orm
register_tortoise(
    app,
    db_url=f"postgres://{getenv('DB_USER', 'postgres')}:{getenv('DB_PASSWORD', 'postgres')}@{getenv('DB_HOST', 'localhost')}:{getenv('DB_PORT', '5432')}/{getenv('DB_NAME', 'postgres')}",
    modules={
        'models': [
            'src.models.user',
            'src.models.customer',
        ]
    },
    generate_schemas=True
)


@app.route("/")
async def index(request: Request):
    return json({"status": True, "message": "Welcome Sanic"})


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080, debug=True, access_log=True)
Esempio n. 6
0
File: pcapid.py Progetto: lxp/pcapid
@app.route('/friend-requests')
async def friend_requests(request):
    unsanitized_session_id = request.token
    try:
        host = await Host.get(session_id=unsanitized_session_id)
    except DoesNotExist:
        abort(401)

    data = {
        'data': [],
        'has_more': False,
    }
    return json(data)


@app.route('/exit-codes', methods=['PUT'])
async def exit_codes(request):
    return json('connection metric not found')


@app.route('/metrics', methods=['PUT'])
async def metrics(request):
    return json(None, status=204)


register_tortoise(app, db_url='sqlite://db.sqlite3', modules={'models': [__name__]}, generate_schemas=True)


if __name__ == '__main__':
    app.run()
Esempio n. 7
0
from sanic import Sanic
from tortoise.contrib.sanic import register_tortoise

from config.configuration import host, port, DB_URL
from view.routes import register_routes

app = Sanic("Project_for_NIT")
register_tortoise(
    app,
    db_url=DB_URL,
    modules={
        'models': ['model.User', 'model.Msg', 'model.Upload', 'model.Token']
    },
    generate_schemas=True)

if __name__ == "__main__":
    register_routes(app=app)
    app.run(host=host, port=port)
Esempio n. 8
0
heliotrope_app.blueprint(heliotrope_routes)

heliotrope_app.config.FALLBACK_ERROR_FORMAT = "json"

mongo = None

if not os.environ.get("BYPASS"):
    heliotrope_app.config.DB_URL = os.environ["DB_URL"]
    heliotrope_app.config.MONGO_DB_URL = os.environ["MONGO_DB_URL"]
    heliotrope_app.config.HIYOBOT_SECRET = os.environ["HIYOBOT_SECRET"]
    register_tortoise(
        heliotrope_app,
        db_url=heliotrope_app.config.DB_URL,
        modules={
            "models": [
                "heliotrope.database.models.hitomi",
                "heliotrope.database.models.requestcount",
            ]
        },
        generate_schemas=True,
    )
    mongo = AsyncIOMotorClient
    if not os.environ.get("IS_TEST"):
        heliotrope_app.config.SENTRY_DSN = os.environ["SENTRY_DSN"]
        heliotrope_app.config.FORWARDED_SECRET = os.environ["FORWARDED_SECRET"]
        sentry_sdk.init(
            dsn=heliotrope_app.config.SENTRY_DSN,
            integrations=[SanicIntegration()],
            release=f"heliotrope@{heliotrope.__version__}",
        )
Esempio n. 9
0
        log.error(__name__ + '.error', status=exception.args[0])
        return sanicjson(dict(status=exception.args[0]),
                         status=exception.status_code)
    else:
        _, _, exc_info = sys.exc_info()
        log.error(__name__ + '.error', exc_info=exc_info)
        return sanicjson(dict(status='bug'), status=500)


register_tortoise(
    app=app,
    db_url=config.DATABASE_URL,
    modules={
        'models': [
            'bawwab.session',
            'bawwab.user',
            'bawwab.action',
            'bawwab.email',
        ]
    },
    generate_schemas=True,
)

app.blueprint(session.bp, url_prefix='/session')
app.blueprint(user.bp, url_prefix='/user')
app.blueprint(action.bp, url_prefix='/action')
app.blueprint(status.bp, url_prefix='/status')
app.blueprint(process.bp, url_prefix='/process')
app.blueprint(csp.bp, url_prefix='/csp')
app.blueprint(filesystem.bp, url_prefix='/filesystem')
app.blueprint(email.bp, url_prefix='/email')
Esempio n. 10
0
app.add_route(CitiesResource.as_view(), '/cities')
app.add_route(CityDetailResource.as_view(), '/cities/<city_id>')
app.add_route(HealthCheckResource.as_view(), '/health')

register_tortoise(
    app=app,
    config={
        'connections': {
            'read':
            f'mysql://{config.db_user}:{config.db_password}@'
            f'{config.db_host_read}:{config.db_port}/{config.db_name}?charset=utf8',
            'write':
            f'mysql://{config.db_user}:{config.db_password}@'
            f'{config.db_host_write}:{config.db_port}/{config.db_name}?charset=utf8'
        },
        "apps": {
            'read': {
                'models': ['app.ports.repos.read_models'],
                'default_connection': 'read'
            },
            'write': {
                "models": ['app.ports.repos.write_models'],
                'default_connection': 'write'
            }
        }
    },
    generate_schemas=False)

register_error_handlers(app)
Esempio n. 11
0
from argparse import ArgumentParser
from tortoise.contrib.sanic import register_tortoise

from config import DB_CONFIG
from app import app
import views

if __name__ == '__main__':
    parser = ArgumentParser(description='Illusory Beacon Backend')
    parser.add_argument('--host', dest='host', type=str, default='0.0.0.0')
    parser.add_argument('--port', dest='port', type=int, default=8000)
    parser.add_argument('--workers', dest='workers', type=int, default=1)
    parser.add_argument('--debug', action="store_true")
    args = parser.parse_args()

    register_tortoise(app, config=DB_CONFIG, generate_schemas=True)

    app.run(host=args.host,
            port=args.port,
            workers=args.workers,
            debug=args.debug)
Esempio n. 12
0
from models import Users
from sanic import Sanic, response

from tortoise.contrib.sanic import register_tortoise

logging.basicConfig(level=logging.DEBUG)

app = Sanic(__name__)


@app.route("/")
async def list_all(request):
    users = await Users.all()
    return response.json({"users": [str(user) for user in users]})


@app.route("/user")
async def add_user(request):
    user = await Users.create(name="New User")
    return response.json({"user": str(user)})


register_tortoise(app,
                  db_url="sqlite://:memory:",
                  modules={"models": ["models"]},
                  generate_schemas=True)

if __name__ == "__main__":
    app.run(port=5000)
Esempio n. 13
0
            user.username,
            "email":
            user.email,
            # Addresses were prefetched
            "addresses": [{
                "address": address.address,
                "zip_code": address.zip_code,
                "city": address.city,
            } for address in user.addresses],
            # Lazy loading of groups
            "groups": [{
                "name": group.name,
            } for group in await user.groups]
        } for user in users
    ])


@app.route("/user/names")
async def list_all_names(request):
    users = await User.all()
    return response.json({"users": [str(user) for user in users]})


if __name__ == "__main__":
    if len(sys.argv) >= 2 and "init" in sys.argv[1:]:
        run_async(init_db())
        sys.exit(0)

    register_tortoise(app, config=TORTOISE_ORM)
    app.run(host="0.0.0.0", port=8080, debug=True)
Esempio n. 14
0
    print (list_of_dicts)
  return response.json(list_of_dicts)

register_tortoise(
    app, generate_schemas=False ,
    config = {
    'connections': {
        # Dict format for connection
        'default': {
            'engine': 'tortoise.backends.asyncpg',
            'credentials': {
                'host': 'localhost',
                'port': '5432',
                'user': '******',
                'password': '******',
                'database': '2fast_api',
                'maxsize' : '1000'
            }
        },
    },
    'apps': {
        'models': {
            'models': ['__main__'],
            # If no default_connection specified, defaults to 'default'
            'default_connection': 'default',
        }
    }
    }
    )


if __name__ == "__main__":
Esempio n. 15
0
"""
init router
"""
app.blueprint(api)
"""
inti mysql
"""
register_tortoise(app,
                  db_url="mysql://{}:{}@{}:{}/{}?maxsize={}&minsize={}".format(
                      get_mysql_data()['user'],
                      get_mysql_data()['password'],
                      get_mysql_data()['host'],
                      get_mysql_data()['port'],
                      get_mysql_data()['dbname'],
                      get_mysql_data()['maxsize'],
                      get_mysql_data()['minsize']),
                  modules={
                      "models": [
                          "models.{}".format(item.replace('.py', ''))
                          for item in os.listdir("./models")
                          if item.endswith(".py")
                      ]
                  },
                  generate_schemas=False)

env = Environment(loader=PackageLoader(__name__, 'templates'))


@app.middleware("request")
async def print_on_request(request):
    log.info("user {} request {} ".format(request.ip, request.path))
Esempio n. 16
0

@app.post('api/test/recovery')
@requires_verification()
async def on_recover(request, verification_session):
    """
    Changes and recovers an account's password.
    """
    await account_recovery(request, verification_session)
    return json('Account recovered successfully',
                verification_session.account.json())


@app.exception(AuthError)
async def on_error(request, exception):
    return json('An error has occurred!', {
        'error': type(exception).__name__,
        'summary': str(exception)
    },
                status_code=exception.status_code)


if __name__ == '__main__':
    register_tortoise(
        app,
        db_url=
        'mysql://*****:*****@personal.cbb4vtpozf6b.us-east-1.rds.amazonaws.com/amyrose',
        modules={"models": ['asyncauth.core.models']},
        generate_schemas=True)
    app.run(host='0.0.0.0', port=8000, debug=True)