Ejemplo n.º 1
0
def create_app(name: str,
               psql_uri: str = None,
               mongo_uri: str = None,
               psql_pool_args: dict = None) -> Pint:
    """
    Create the core API app. Supply URIs as necessary
    """
    app = Pint(name)

    @app.before_serving
    async def _startup():
        if psql_uri:
            import asyncpg

            kwargs = {"min_size": 3, "max_size": 8, "command_timeout": 5}
            if "localhost" not in psql_uri:
                kwargs["ssl"] = SSLContext()
            if psql_pool_args:
                kwargs.update(psql_pool_args)
            app.db = await asyncpg.create_pool(psql_uri, **kwargs)
        else:
            app.db = None

        if mongo_uri:
            from motor.motor_asyncio import AsyncIOMotorClient

            app.mdb = AsyncIOMotorClient(mongo_uri)
        else:
            app.mdb = None

    app.json_encoder = CustomJSONEncoder
    app.after_request(add_cors)
    return app
Ejemplo n.º 2
0
def create_app(config) -> Pint:
    load_dotenv(verbose=True)

    app = Pint(__name__,
               title="BattleShip",
               base_model_schema=BASE_MODEL_SCHEMA)
    app = cors(app, allow_origin="*")
    app.json_encoder = Encoder

    app.config.from_envvar("CONFIG_FILE")

    app.games = dict()

    @app.before_serving
    async def init_orm():
        await init()

    from battlefield.session.data.api.single import session
    app.register_blueprint(session)

    from battlefield.session.data.api.multi import sessions
    app.register_blueprint(sessions)

    from battlefield.game.data.websocket import game
    app.register_blueprint(game)

    @app.cli.command()
    def openapi():
        print(json.dumps(app.__schema__, indent=4, sort_keys=False))

    @app.after_serving
    async def close_orm():
        await Tortoise.close_connections()

    return app
Ejemplo n.º 3
0
def app():
    testapp = Pint('test',
                   title='App Test',
                   contact='foo',
                   contact_email='*****@*****.**',
                   description='Sample Desc')
    return testapp
Ejemplo n.º 4
0
    def __init__(self, **kwargs):
        self.init_keys = set()

        for k, v in kwargs.items(
        ):  # TODO figure out how to distinguish between Models in Mongo and Postgres
            setattr(self, k, v)
            self.init_keys.add(k)

        for k, v in self.DEFAULT_VALUES.items():
            if k not in kwargs:
                setattr(self, k, v)
            else:
                setattr(self, k, kwargs.get(k))

        self.logger = Logger(self.NAME)

        self.app = Pint(self.NAME)
        self.app.config.update(DBSettings.get_mongo_config(**kwargs))
        self.app.config.update(DBSettings.get_sqlalchemy_config(**kwargs))

        self.orm_mappings = {}
        self.odm_mappings = {}
        self.default_mongo_settings = {}
        self.default_sqlalchemy_settings = {}

        self.default_mongo_engine = None
        self.default_sqla_engine = None

        self.views = []
        if isinstance(kwargs.get(VIEWS, list()), list):
            for v in kwargs.get(VIEWS, list()):
                self.import_add_view(v)

        if self.get_using_mongo():
            self.default_mongo_settings = DBSettings.get_mongoclient_kargs(
                **kwargs)
            self.default_mongo_settings[TLS_INSECURE] = True
            if self.default_mongo_settings.get(SSL_KEYFILE, None) is None:
                self.default_mongo_settings[SSL_KEYFILE] = self.get_key_pem()
            if self.default_mongo_settings.get(SSL_CERTFILE, None) is None:
                self.default_mongo_settings[SSL_KEYFILE] = self.get_cert_pem()

        if self.get_using_postgres():
            self.default_sqlalchemy_settings = DBSettings.get_sqlalchemy_config(
                **kwargs)
            uri = self.pgc.get(SQLALCHEMY_DATABASE_URI)
            self.default_sqla_engine = create_engine(uri)

            for name, kargs in self.get_sqlalchemy_orms():
                classname = kargs.get(ORM_CLASS, None)
                tablename = kargs.get(TABLE, None)

                if classname is None or tablename is None:
                    continue
                self.import_add_orms(classname, tablename)

        self.load_odm_configurations(self.get_odms())
        self.load_orm_configurations(self.get_orms())
        self.bg_thread = None
Ejemplo n.º 5
0
def test_base_model_file(tmpdir):
    import json
    tmp_schema = tmpdir.join('schema.json')
    tmp_schema.write_text(json.dumps(TEST_BASE_MODEL_SCHEMA), encoding='utf-8')

    app = Pint('test', base_model_schema=str(tmp_schema.realpath()))

    assert isinstance(app.base_model, RefResolver)
    assert app.base_model.base_uri == 'schema.json'
Ejemplo n.º 6
0
async def test_no_openapi():
    app = Pint('test',
               title='App Test',
               contact='foo',
               contact_email='*****@*****.**',
               no_openapi=True)
    client = app.test_client()
    rv = await client.get('/openapi.json')
    assert rv.status_code == HTTPStatus.NOT_FOUND
Ejemplo n.º 7
0
def create_app(name: str, mongo_uri: str = None) -> Pint:
    """Create the core API app. Supply URIs as necessary"""
    app = Pint(name)

    @app.before_serving
    async def _startup():
        app.mdb = AsyncIOMotorClient(mongo_uri) if mongo_uri else None

    app.json_encoder = CustomJSONEncoder
    app.after_request(add_cors)
    return app
Ejemplo n.º 8
0
async def test_base_model_obj():
    app = Pint('test',
               title='App Test',
               contact='foo',
               contact_email='*****@*****.**',
               description='Sample Desc',
               base_model_schema=TEST_BASE_MODEL_SCHEMA)

    @app.route('/testque')
    @app.param('test_que', ref='#/components/parameters/test_query')
    class TestQue(Resource):
        async def get(self):
            return request.args['moo']

    test_que_ref = app.create_ref_validator('test_query', 'parameters')

    @app.route('/testref')
    @app.param('test_que_ref', ref=test_que_ref)
    class TestRef(Resource):
        async def get(self):
            return request.args['moo']

    @app.route('/testquename')
    @app.param('test_que_name', ref='test_query')
    class TestQueName(Resource):
        async def get(self):
            return request.args['moo']

    swag = app.__schema__
    assert swag['components']['parameters']['test_query']['name'] == 'moo'
    swag_testque = swag['paths']['/testque']['get']
    swag_testref = swag['paths']['/testref']['get']
    swag_testquename = swag['paths']['/testquename']['get']
    assert swag_testque['parameters'] == swag_testref['parameters']
    assert swag_testque['parameters'] == swag_testquename['parameters']

    client = app.test_client()

    rv = await client.get('/testque?moo=foo')
    assert rv.status_code == HTTPStatus.OK
    assert await rv.get_data() == b'foo'

    rv = await client.get('/testref?moo=bar')
    assert rv.status_code == HTTPStatus.OK
    assert await rv.get_data() == b'bar'

    rv = await client.get('/testquename?moo=baz')
    assert rv.status_code == HTTPStatus.OK
    assert await rv.get_data() == b'baz'
Ejemplo n.º 9
0
async def test_custom_openapi():
    app = Pint('test',
               title='App Test',
               contact='foo',
               no_openapi=True,
               contact_email='*****@*****.**')

    @app.route('/hello')
    class Hello(Resource):
        async def get(self):
            return "OK"

    @app.route('/api.json', methods=['GET', 'OPTIONS'])
    async def api():
        return jsonify(app.__schema__)

    client = app.test_client()
    rv = await client.get('/api.json')
    assert rv.status_code == HTTPStatus.OK

    data = await rv.get_json()
    assert data == {
        'openapi': '3.0.0',
        'info': {
            'title': 'App Test',
            'version': '1.0',
            'contact': {
                'name': 'foo',
                'email': '*****@*****.**'
            }
        },
        'servers': [{
            'url': 'http://'
        }],
        'paths': {
            '/hello': {
                'get': {
                    'description': '',
                    'tags': [],
                    'responses': {
                        '200': {
                            'description': 'Success'
                        }
                    },
                    'operationId': 'get_hello'
                }
            }
        }
    }
Ejemplo n.º 10
0
async def test_required_query():
    app = Pint('test', title='App Test', contact='foo',
                  contact_email='*****@*****.**', description='Sample Desc',
                  base_model_schema=TEST_BASE_MODEL_SCHEMA)

    test_que_ref = app.create_ref_validator('test_query', 'parameters')

    @app.param('test_que_ref', _in='query', schema=test_que_ref)
    @app.route('/testref')
    def testref():
        return request.args['moo']

    client = app.test_client()
    rv = await client.get('/testref')
    # will add validation in the future for required query args
    assert rv.status_code == HTTPStatus.BAD_REQUEST
Ejemplo n.º 11
0
def make_app():
    app = Pint(__name__, title="Rhasspy")
    app = cors(app)

    @app.route("/")
    class Root(Resource):
        async def get(self):
            """Hello World Route

        This docstring will show up as the description and short-description
        for the openapi docs for this route.
        """
            return "hello"

    @app.websocket("/ws")
    async def ws():
        while True:
            await websocket.send("hello")
Ejemplo n.º 12
0
def create_app():
    from . import models, resources, schemas, logger, repositories, injection

    app = Pint(__name__, title='Magnum Opus')

    # This could be used to separate by environment
    app.config.from_object('magnumopus.config.Config')

    # This helps avoid cyclic dependencies
    modules = []

    modules += logger.init_app(app)
    modules += models.init_app(app)
    modules += resources.init_app(app)
    modules += repositories.init_app(app)
    modules += schemas.init_app(app)

    injection.init_app(app, modules)

    return app
Ejemplo n.º 13
0
async def test_post_validation():
    app = Pint('test', base_model_schema=TEST_BASE_MODEL_SCHEMA)

    test_ref = app.create_ref_validator('User', 'schemas')

    @app.route('/testroute')
    class TestReq(Resource):
        @app.expect(test_ref)
        async def post(self):
            return jsonify(await request.get_json())

    client = app.test_client()

    # fail validation, missing required props
    rv = await client.post('/testroute', json={})
    assert rv.status_code == HTTPStatus.BAD_REQUEST
    assert rv.headers['content-type'] == 'application/json'
    data = await rv.get_json()
    assert data['message'] == 'Request Body failed validation'
    assert 'msg' in data['error'] and data['error']['msg']
    assert 'value' in data['error']
    assert 'schema' in data['error']

    # fail validation, have required props, but age is wrong type
    rv = await client.post('/testroute', json={'name': 'foobar', 'age': 'baz'})
    assert rv.status_code == HTTPStatus.BAD_REQUEST
    assert rv.headers['content-type'] == 'application/json'
    data = await rv.get_json()
    assert data['message'] == 'Request Body failed validation'
    assert 'msg' in data['error'] and data['error']['msg']
    assert 'value' in data['error']
    assert 'schema' in data['error']

    # succeed validation
    rv = await client.post('/testroute', json={'name': 'foobar', 'age': 10})
    assert rv.status_code == HTTPStatus.OK
Ejemplo n.º 14
0
def create_app(config_class=Development) -> Pint:
    app = Pint(__name__)
    app.test_client()
    DbWrapper.set_url(config_class.SQLALCHEMY_DATABASE_URI)
    db = DbWrapper.create_instance()

    @app.before_request
    async def connect_db() -> None:
        # todo: replace Exception with AlreadyConnectedToDbException
        try:
            await db.connect()
        except Exception:
            pass

    @app.after_request
    async def disconnect_db(response) -> None:
        await db.disconnect()
        return response

    app.config.from_object(Development)
    register_blueprints(app)

    app = cors(app, allow_credentials=True)
    return app
Ejemplo n.º 15
0
def test_base_model_ref_resolve():
    base_model = RefResolver.from_schema(TEST_BASE_MODEL_SCHEMA)
    app = Pint('test', base_model_schema=base_model)

    assert isinstance(app.base_model, RefResolver)
    assert app.base_model.base_uri == 'schema.json'
Ejemplo n.º 16
0
    if session_key in session_clients:
        return session_clients[session_key]['client']

    print('Creating new session client with key ', session_key)
    new_client = TelegramClient('api_test_' + session_key, API_ID, API_HASH)
    new_client.session.set_dc(2, '149.154.167.40', 443)
    session_clients[session_key] = {}
    session_clients[session_key]['client'] = new_client

    await new_client.connect()

    return new_client


# Quart app
app = Pint(__name__, title='apiMiddleware')
app.secret_key = 'Someday this war will end'
app = cors(app, allow_origin='http://localhost:8080', allow_credentials=True)

# VALIDATORS


# After we're done serving (near shutdown), clean up the client
@app.after_serving
async def cleanup():
    for client in session_clients.items():
        await client[1]['client'].disconnect()


@app.route('/')
class Root(Resource):
Ejemplo n.º 17
0
from quart import Quart, request, jsonify
from quart_openapi import Pint, Resource

from telethon import TelegramClient
import logging
logging.basicConfig(
  format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s',
  level=logging.WARNING
)

app = Pint(__name__, title='mtproto-proxy')

api_id = 1150044
api_hash = "07a4a593788b5d222f4f3139dca2e0b9"

async def main(client, phone_number):
  print('here we go')
  response = await client.send_code_request(phone_number, True)

  print(response.stringify())

@app.route('/auth.sendCode')
class SendCode(Resource):
  async def post(self):
    data = await request.get_json()
    phone_number = data['phone_number']
    print(phone_number)
    client = TelegramClient('anon', api_id, api_hash)
    await client.connect()
    sent = await client.send_code_request(phone_number)
    response = {
Ejemplo n.º 18
0
"""A Quart application module for the rate limiting proxy solution.
Uses REQUEST_COUNT and INTERVAL environment variables to configure the rate for
a root ("/") endpoint.
Replies Hello! to all valid requests. Rejects all rate exceeding requests with
429 statius code.
"""
import os
from quart import Quart, redirect, url_for
from quart_openapi import Pint, Resource
from decorators.rate_limit import rate_limit

REQUEST_COUNT = os.getenv("REQUEST_COUNT", "1")
INTERVAL = os.getenv("INTERVAL", "5")

PROXY = Pint(__name__, title="Rate Limiting Proxy App")


@PROXY.route("/")
class RateLimitProxyRoot(Resource):
    """This route is used to limit the rate of the incoming requests to a
    configured REQUEST_COUNT per INTERVAL. The configuration is read from
    the environment.
    """
    @rate_limit(int(REQUEST_COUNT), int(INTERVAL))
    async def get(self):
        """Get request.
        """
        return "Hello!"


if __name__ == "__main__":
Ejemplo n.º 19
0
from os import environ

from quart_openapi import Pint

import service.config as default_config

app = Pint(__name__, no_openapi=True, title='Exact Time Service')
app.config.from_object(default_config)

config_file = environ.get('QUART_CONFIG')
if config_file:
    app.config.from_pyfile(config_file)

import service.view
Ejemplo n.º 20
0
from quart_openapi import Pint, Resource
from quart import jsonify, request

app = Pint(__name__, title='Spectacular Hypercorn Quart Application Skeleton')

expected = app.create_validator('sample_request', {
  'type': 'object',
  'properties': {
    'foobar': {
      'type': 'string'
    },
    'baz': {
      'oneOf': [
        { 'type': 'integer' },
        { 'type': 'number', 'format': 'float' }
      ]
    }
  }
})

@app.route('/')
class Root(Resource):
  async def get(self):
    '''Note Route

    This docstring will show up as the description and short-description
    for the openapi docs for this route.
    '''
    return jsonify({"Note": "There exists a localhost:9000/openapi.json that can be helpful here"})
  @app.expect(expected)
  async def post(self): 
Ejemplo n.º 21
0
                return action
            elif action.metavar == name:
                return action
            elif action.dest == name:
                return action

    def error(self, message):
        exc = sys.exc_info()[1]
        if exc:
            exc.argument = self._get_action_from_name(exc.argument_name)
            raise exc
        # super(SrlArgumentParser, self).error(message)

# small restful API server running locally so my other bots can send messages

app = Pint(__name__, title='Srl Bot API')

@app.route('/api/message')
class Message(Resource):
    async def post(self):
        data = await request.get_json()
        if 'auth' in data and data['auth'] == c.InternalApiToken:
            if not client.in_channel(data['channel']):
                abort(400, "Bot not in specified channel")
            result = await client.message(data['channel'], data['message'])
            return jsonify({"success": True})
        else:
            abort(401)

if __name__ == '__main__':
    client = SrlBot(c.SRL_NICK, realname=c.SRL_NICK)
Ejemplo n.º 22
0
""":mod:'irastretto.web.app'
--- Quart application

Todo:
    * Download Queue (Modular Structure).
    * Download images from Twitter (Queue Module).
    * Caching duplicated reference.
    * Extract Zelda.
    * User login.
    * Accounts Management.
    * Download images from Pixiv (Queue Module).
    * Library interface.
    * Audio/Video Play.
    * Share Timeline.
    * Finder Extension (Another Project).
"""

from quart_openapi import Pint
from quart_cors import cors

from . import blueprints
from .. import config

app = Pint(__name__, title='Irastretto', template_folder='templates')
app = cors(app)
# app.config.from_object()

app.register_blueprint(blueprints.root.blueprint)
app.register_blueprint(blueprints.tasks.blueprint)
app.register_blueprint(blueprints.users.blueprint)
Ejemplo n.º 23
0
from quart_openapi import Pint

app = Pint(__name__, title='SahasrahBot API')
Ejemplo n.º 24
0
"""

# stdlib
from datetime import date
from os import environ

# library
from motor.motor_asyncio import AsyncIOMotorClient
from quart import got_request_exception
from quart.json import JSONEncoder
from quart_openapi import Pint
import rollbar

from rollbar.contrib.quart import report_exception

app = Pint(__name__)


class CustomJSONEncoder(JSONEncoder):
    # pylint: disable=method-hidden
    def default(self, obj):
        try:
            if isinstance(obj, date):
                return obj.isoformat() + "Z"
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, obj)
Ejemplo n.º 25
0
dictConfig({
    "version": 1,
    "loggers": {
        "quart.app": {
            "level": "DEBUG",
        },
        "quart.serving": {
            "level": "DEBUG"
        },
        "stocks.stocks": {
            "level": "INFO"
        },
    },
})

app = Pint(__name__, title="Stock Analysis")

app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config["STOCKS_FOLDER"] = os.path.join(app.static_folder, "stocks")
blueprint.stocks_folder = os.path.join(app.static_folder, "stocks")

app.register_blueprint(blueprint)


@app.route("/", methods=["GET", "POST"], provide_automatic_options=False)
class Root(Resource):
    async def get(self):
        return await render_template("index.html")


status_expected_schema = app.create_validator("status", {
Ejemplo n.º 26
0
from quart_openapi import Pint

app = Pint("vanguard_api")