Esempio n. 1
0
#!/usr/bin/env python3
from sanic import Sanic
from storage.node_info import NodeInfo
from storage.token_auth import SanicTokenAuth
from sanic.response import json
from aioconsole import ainput
from requests_async import post
from requests_async import ConnectionError
import json as _json
import uuid

app = Sanic(name="node")
memory = NodeInfo()
auth = SanicTokenAuth(token_verifier=memory.is_valid_token)


@app.route("/auth", methods=["POST"])
async def auth_key(request):
    token = str(uuid.uuid4())
    await memory.add_client_api_key(token)
    await distribute({"token": token}, "/registerkey")
    return json({"api-key": token}, status=200)


@app.route("/clusterinfo", methods=["GET"])
async def get_cluster_info(request):
    data = list(memory.get_cluster_nodes())
    data.append(memory.self_url)
    return json({"addresses": data}, status=200)

Esempio n. 2
0
def test_app_registry():
    instance = Sanic("test")
    assert Sanic._app_registry["test"] is instance
Esempio n. 3
0
def test_app_registry_retrieval_from_multiple():
    instance = Sanic("test")
    Sanic("something_else")
    assert Sanic.get_app("test") is instance
Esempio n. 4
0
from aioredis import create_connection, create_redis
from jinja2 import Environment, PackageLoader, select_autoescape
from sanic import Sanic
from sanic.response import json, html
from sanic.websocket import WebSocketProtocol

from chat_sanic.chat import init_chat
from chat_sanic.views import init_views

app = Sanic()

env = Environment(loader=PackageLoader('chat_sanic', 'templates'),
                  autoescape=select_autoescape(['html', 'xml']))


def render_template(name, *args, **kwargs):
    template = env.get_template(name)
    template = template.render(*args, **kwargs)
    return html(template)


@app.listener('before_server_start')
async def setup_redis(app, loop):
    redis = await create_redis('redis://localhost', loop=loop)
    app.redis = redis


@app.get('/status')
def status(request):
    return json({'data': request.ip})
Esempio n. 5
0
from utils import color_print

if not SERVER.DEBUG:
    if version == '0.6':
        LOGGING['loggers']['network']['level'] = 'WARNING'
        LOGGING['loggers']['sanic']['level'] = 'WARNING'
    elif version == '0.7':
        LOGGING['loggers']['sanic.error']['level'] = 'WARNING'
        LOGGING['loggers']['sanic.access']['level'] = 'WARNING'
        LOGGING['loggers']['root']['level'] = 'WARNING'
        LOGGING['loggers']['sanic.access']['handlers'] = ['error_console']
        LOGGING['handlers']['error_console']['stream'] = stdout
        LOGGING['formatters']['generic'][
            'format'] = '%(asctime)s -  %(levelname).4s - %(name)11.11s : %(message)s'

app = Sanic(log_config=LOGGING)
# TODO change the orgins from * to config one (proper one)
CORS(app, automatic_options=True, esources={r"/api/*": {"origins": "*"}})


@app.middleware('response')
async def custom_banner(request, response):
    if request.path.startswith('/api'):
        response.headers["content-type"] = "application/json"
    return response


try:
    context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
    context.load_cert_chain(SERVER.CERT, keyfile=SERVER.PRIVKEY)
    port = SERVER.PORT_HTTPS
Esempio n. 6
0
def test_load_env_prefix_float_values():
    environ["MYAPP_TEST_ROI"] = "2.3"
    app = Sanic(name=__name__, load_env="MYAPP_")
    assert app.config.TEST_ROI == 2.3
    del environ["MYAPP_TEST_ROI"]
Esempio n. 7
0
from sanic import Sanic

from blueprints.car import blueprint as car_blueprint
from blueprints.driver import blueprint as driver_blueprint
from blueprints.garage import blueprint as garage_blueprint
from blueprints.manufacturer import blueprint as manufacturer_blueprint
from blueprints.repair import blueprint as repair_blueprint
from sanic_openapi import swagger_blueprint

app = Sanic("Cars API example")

app.blueprint(swagger_blueprint)
app.blueprint(car_blueprint)
app.blueprint(driver_blueprint)
app.blueprint(garage_blueprint)
app.blueprint(manufacturer_blueprint)
app.blueprint(repair_blueprint)

app.config.API_VERSION = '1.0.0'
app.config.API_TITLE = 'Car API'
app.config.API_TERMS_OF_SERVICE = 'Use with caution!'
app.config.API_CONTACT_EMAIL = '*****@*****.**'
app.config.API_DESCRIPTION = 'Cars API example'

app.run(host="0.0.0.0", debug=True)
Esempio n. 8
0
def create_app(**kwargs):
    app = Sanic(__name__)
    app.blueprint(api)
    add_swagger(app, "/api/swagger.json", "/api/docs")
    return app
Esempio n. 9
0
from sanic.response import json as sanic_json, text, HTTPResponse

from core import load_config
from core.db import ConnectionPool
from core.loggers import AioReporter
from core.openapi import blueprint as openapi_blueprint
from core.service import ServiceManager, service_watcher
from core.exceptions import Unauthorized
from core.utils import CustomHandler, consume, before_request
from utils.auth import JSONWebTokenAuthentication

config = load_config()
app_name = config.get('SERVICE_NAME', __name__)
consul_enabled = config.get('CONSUL_ENABLED', False)
logging_config = config.get('LOGGING_CONFIG', None)
app = Sanic(app_name, error_handler=CustomHandler(), log_config=logging_config)
app.config = config
app.blueprint(openapi_blueprint)


@app.listener('before_server_start')
async def before_server_start(app, loop):
    queue = asyncio.Queue()
    app.queue = queue
    if consul_enabled:
        app.service_manager = ServiceManager(
            consul_host=app.config['CONSUL_AGENT_HOST'],
            consul_port=app.config['CONSUL_AGENT_PORT'],
            loop=loop,
        )
        loop.create_task(service_watcher(app, loop))
Esempio n. 10
0

def print_time(f):
    @wraps(f)
    async def decorated_function(request, *args, **kwargs):
        start = time.time()
        response = await f(request, *args, **kwargs)
        end = time.time()
        spend = end - start
        logger.info(f"spend {spend} s")
        return response

    return decorated_function


app = Sanic(log_config=LOGGING_CONFIG_JSON)
api_user = Blueprint('api_user')

User = []

User_Schema = {
    "title": "User",
    "description": "用户",
    "type": "object",
    "properties": {
        "name": {
            "description": "user name",
            "type": "string"
        },
        "age": {
            "description": "user age",
Esempio n. 11
0
    args = parser.parse_args()

    cur_instance = args.instance
    nb_replica = args.nb_replica
    sanic_port = args.sanic_port

    try:
        cur_instance = int(cur_instance)
    except ValueError:
        print('Bad instance !')
        exit(-1)

    BASE_DIR = os.path.dirname(os.path.abspath(__file__))

    # Creates sanic server
    sanic = Sanic(name=f'cash-register-{cur_instance}')

    # Creates cash register dict app
    cash_register_app = dict()

    cash_register_app['instance'] = cur_instance
    cash_register_app['nb_replica'] = nb_replica

    # Registers logger
    cash_register_app['logger'] = setup_logger()

    cash_register_app['logger'].info(f'Current cash register instance : {cur_instance}')

    # Creates & registers event loop
    cash_register_app['loop'] = uvloop.new_event_loop()
    asyncio.set_event_loop(cash_register_app['loop'])
Esempio n. 12
0
def main():
    parser = argparse.ArgumentParser(description='Run the demo server')
    parser.add_argument('model', help='Models to use')

    parser.add_argument(
        '-v',
        '--voc',
        help='vocab to use, only words from this file will be used')
    parser.add_argument('-t',
                        '--tokens',
                        type=int,
                        default=400,
                        help='Number of tokens to use per paragraph')
    parser.add_argument('--vec_dir', help='Location to find word vectors')
    parser.add_argument('--n_paragraphs',
                        type=int,
                        default=12,
                        help="Number of paragraphs to run the model on")
    parser.add_argument('--span_bound',
                        type=int,
                        default=8,
                        help="Max span size to return as an answer")

    parser.add_argument(
        '--tagme_api_key',
        help="Key to use for TAGME (tagme.d4science.org/tagme)")
    parser.add_argument('--bing_api_key', help="Key to use for bing searches")
    parser.add_argument('--tagme_thresh', default=0.2, type=float)
    parser.add_argument('--no_wiki',
                        action="store_true",
                        help="Dont use TAGME")
    parser.add_argument('--n_web',
                        type=int,
                        default=10,
                        help='Number of web docs to fetch')
    parser.add_argument('--blacklist_trivia_sites',
                        action="store_true",
                        help="Don't use trivia websites")
    parser.add_argument('-c',
                        '--wiki_cache',
                        help="Cache wiki articles in this directory")

    parser.add_argument('--n_dl_threads',
                        type=int,
                        default=5,
                        help="Number of threads to download documents with")
    parser.add_argument('--request_timeout', type=int, default=60)
    parser.add_argument('--download_timeout', type=int, default=25)
    parser.add_argument('--workers',
                        type=int,
                        default=1,
                        help="Number of server workers")
    parser.add_argument('--debug',
                        default=None,
                        choices=["random_model", "dummy_qa"])

    args = parser.parse_args()
    span_bound = args.span_bound

    if args.tagme_api_key is not None:
        tagme_api_key = args.tagme_api_key
    else:
        tagme_api_key = environ.get("TAGME_API_KEY")

    if args.bing_api_key is not None:
        bing_api_key = args.bing_api_key
    else:
        bing_api_key = environ.get("BING_API_KEY")
        if bing_api_key is None and args.n_web > 0:
            raise ValueError("If n_web > 0 you must give a BING_API_KEY")

    if args.debug is None:
        model = ModelDir(args.model)
    else:
        model = RandomPredictor(5, WithIndicators())

    if args.vec_dir is not None:
        loader = LoadFromPath(args.vec_dir)
    else:
        loader = ResourceLoader()

    if args.debug == "dummy_qa":
        qa = DummyQa()
    else:
        qa = QaSystem(
            args.wiki_cache,
            MergeParagraphs(args.tokens),
            ShallowOpenWebRanker(args.n_paragraphs),
            args.voc,
            model,
            loader,
            bing_api_key,
            tagme_api_key=tagme_api_key,
            n_dl_threads=args.n_dl_threads,
            blacklist_trivia_sites=args.blacklist_trivia_sites,
            download_timeout=args.download_timeout,
            span_bound=span_bound,
            tagme_threshold=None if args.no_wiki else args.tagme_thresh,
            n_web_docs=args.n_web)

    logging.propagate = False
    formatter = logging.Formatter("%(asctime)s: %(levelname)s: %(message)s")
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    logging.root.addHandler(handler)
    logging.root.setLevel(logging.DEBUG)

    app = Sanic()
    app.config.REQUEST_TIMEOUT = args.request_timeout

    @app.route("/answer")
    async def answer(request):
        try:
            question = request.args["question"][0]
            if question == "":
                return response.json({'message': 'No question given'},
                                     status=400)
            spans, paras = await qa.answer_question(question)
            answers = select_answers(paras, spans, span_bound, 10)
            return json([x.to_json() for x in answers])
        except Exception as e:
            log.info("Error: " + str(e))

            raise ServerError("Server Error", status_code=500)

    @app.route('/answer-from', methods=['POST'])
    async def answer_from(request):
        try:
            args = ujson.loads(request.body.decode("utf-8"))
            question = args.get("question")
            if question is None or question == "":
                return response.json({'message': 'No question given'},
                                     status=400)
            doc = args["document"]
            if len(doc) > 500000:
                raise ServerError("Document too large", status_code=400)
            spans, paras = qa.answer_with_doc(question, doc)
            answers = select_answers(paras, spans, span_bound, 10)
            return json([x.to_json() for x in answers])
        except Exception as e:
            log.info("Error: " + str(e))
            raise ServerError("Server Error", status_code=500)

    app.static('/', './docqa//server/static/index.html')
    app.static('/about.html', './docqa//service/static/about.html')
    app.run(host="0.0.0.0", port=8000, workers=args.workers, debug=False)
        if hasattr(base_add, '__wrapped__'):
            base_add = base_add.__wrapped__
        return base_add(self, *args, **kwargs)

    def get(self, request):
        base_get = Router.get
        if hasattr(base_get, '__wrapped__'):
            base_get = base_get.__wrapped__

        handler, args, kwargs, uri = base_get(self, request)
        if request.path == '/server-error':
            handler = None
        return handler, args, kwargs, uri


app = Sanic(error_handler=CustomErrorHandler(), router=CustomRouter())


@app.route('/')
async def index(request):
    return json({'hello': 'world'})


@app.route('/error')
async def error(request):
    raise ValueError('Exception')


# see write_callback in confest.create_request_coroutine
@app.route('/write_response_error')
async def write_response_error(request):
Esempio n. 14
0
    def __init__(self, request_delay=None, *args, **kwargs) -> None:
        dispatch = DelayableSanicConnectionPool(request_delay=request_delay)
        super().__init__(dispatch=dispatch, *args, **kwargs)


class DelayableSanicTestClient(SanicTestClient):
    def __init__(self, app, request_delay=None):
        super().__init__(app)
        self._request_delay = request_delay
        self._loop = None

    def get_new_session(self):
        return DelayableSanicSession(request_delay=self._request_delay)


request_timeout_default_app = Sanic("test_request_timeout_default")
request_no_timeout_app = Sanic("test_request_no_timeout")
request_timeout_default_app.config.REQUEST_TIMEOUT = 0.6
request_no_timeout_app.config.REQUEST_TIMEOUT = 0.6


@request_timeout_default_app.route("/1")
async def handler1(request):
    return text("OK")


@request_no_timeout_app.route("/1")
async def handler2(request):
    return text("OK")

Esempio n. 15
0
def test_dont_load_env():
    environ["SANIC_TEST_ANSWER"] = "42"
    app = Sanic(name=__name__, load_env=False)
    assert getattr(app.config, "TEST_ANSWER", None) is None
    del environ["SANIC_TEST_ANSWER"]
Esempio n. 16
0
import asyncio

from signal import SIGINT, signal

import uvloop

from sanic import Sanic, response
from sanic.server import AsyncioServer

app = Sanic("Example")


@app.before_server_start
async def before_server_start(app, loop):
    print("Async Server starting")


@app.after_server_start
async def after_server_start(app, loop):
    print("Async Server started")


@app.before_server_stop
async def before_server_stop(app, loop):
    print("Async Server stopping")


@app.after_server_stop
async def after_server_stop(app, loop):
    print("Async Server stopped")
Esempio n. 17
0
def test_load_env_prefix():
    environ["MYAPP_TEST_ANSWER"] = "42"
    app = Sanic(name=__name__, load_env="MYAPP_")
    assert app.config.TEST_ANSWER == 42
    del environ["MYAPP_TEST_ANSWER"]
Esempio n. 18
0
from sanic import Sanic
from sanic.response import json
from sanic_cors import CORS

from api.users.routes import users_routes
from util.middlewares import handle_request, handle_response

# Start the app and load environment variables.
app = Sanic(load_env=True)
app.config.from_envvar('ENV_VARS')
CORS(app)


# root route
@app.route('/')
async def root(request):
    return json({}, status=200)


# Register all blueprints.
app.blueprint(users_routes)

# Register all middlewares.
app.register_middleware(handle_request, 'request')
app.register_middleware(handle_response, 'response')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)
Esempio n. 19
0
def test_load_env_prefix_string_value():
    environ["MYAPP_TEST_TOKEN"] = "somerandomtesttoken"
    app = Sanic(name=__name__, load_env="MYAPP_")
    assert app.config.TEST_TOKEN == "somerandomtesttoken"
    del environ["MYAPP_TEST_TOKEN"]
Esempio n. 20
0
                self,
                "%s Client running in http mode, careful now !" % self.id)
            app.run(host=self.configuration.client_configuration.host,
                    port=self.configuration.client_configuration.port,
                    debug=self.configuration.client_configuration.debug,
                    workers=self.configuration.client_configuration.workers)

        self.shutdown()


if __name__ == '__main__':
    REST_CLIENT = None

    outputLog(None, "Initiating Sanic REST Service...")

    APP = Sanic()

    @APP.route('/api/rest/v1.0/ask', methods=['GET', 'POST'])
    async def ask(request):
        response, status = REST_CLIENT.process_request(request, version=1.0)
        return REST_CLIENT.create_response(response,
                                           status_code=status,
                                           version=1.0)

    @APP.route('/api/rest/v2.0/ask', methods=['GET', 'POST'])
    async def ask(request):
        response, status = REST_CLIENT.process_request(request, version=2.0)
        return REST_CLIENT.create_response(response,
                                           status_code=status,
                                           version=2.0)
#!/usr/bin/env python3
from sanic import Sanic
from sanic import response
from sanic.exceptions import NotFound
import pickle as cPickle

from handler.services import services

app = Sanic(__name__)
app.blueprint(services)
app.config['model_path'] = './model/train_model.clf'

@app.listener('before_server_start')
async def init(sanic, loop):
    with open(app.config['model_path'], 'rb') as train_model:
        knn_classifier = cPickle.load(train_model)
        app.config['db'] = knn_classifier

@app.listener('after_server_stop')
async def close_connection(app, loop):
    pass

@app.exception(NotFound)
async def ignore_404s(request, exception):
    return response.json({'status': 500, 'message': 'Route not found'})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=19999, debug=True, workers=4)
Esempio n. 22
0
    def app(self):
        app = Sanic(__name__)
        default_templates = str(app_root / "datasette" / "templates")
        template_paths = []
        if self.template_dir:
            template_paths.append(self.template_dir)
        template_paths.extend(
            [
                plugin["templates_path"]
                for plugin in get_plugins(pm)
                if plugin["templates_path"]
            ]
        )
        template_paths.append(default_templates)
        template_loader = ChoiceLoader(
            [
                FileSystemLoader(template_paths),
                # Support {% extends "default:table.html" %}:
                PrefixLoader(
                    {"default": FileSystemLoader(default_templates)}, delimiter=":"
                ),
            ]
        )
        self.jinja_env = Environment(loader=template_loader, autoescape=True)
        self.jinja_env.filters["escape_css_string"] = escape_css_string
        self.jinja_env.filters["quote_plus"] = lambda u: urllib.parse.quote_plus(u)
        self.jinja_env.filters["escape_sqlite"] = escape_sqlite
        self.jinja_env.filters["to_css_class"] = to_css_class
        pm.hook.prepare_jinja2_environment(env=self.jinja_env)
        app.add_route(IndexView.as_view(self), r"/<as_format:(\.jsono?)?$>")
        # TODO: /favicon.ico and /-/static/ deserve far-future cache expires
        app.add_route(favicon, "/favicon.ico")
        app.static("/-/static/", str(app_root / "datasette" / "static"))
        for path, dirname in self.static_mounts:
            app.static(path, dirname)
        # Mount any plugin static/ directories
        for plugin in get_plugins(pm):
            if plugin["static_path"]:
                modpath = "/-/static-plugins/{}/".format(plugin["name"])
                app.static(modpath, plugin["static_path"])
        app.add_route(
            JsonDataView.as_view(self, "inspect.json", self.inspect),
            r"/-/inspect<as_format:(\.json)?$>",
        )
        app.add_route(
            JsonDataView.as_view(self, "metadata.json", lambda: self._metadata),
            r"/-/metadata<as_format:(\.json)?$>",
        )
        app.add_route(
            JsonDataView.as_view(self, "versions.json", self.versions),
            r"/-/versions<as_format:(\.json)?$>",
        )
        app.add_route(
            JsonDataView.as_view(self, "plugins.json", self.plugins),
            r"/-/plugins<as_format:(\.json)?$>",
        )
        app.add_route(
            JsonDataView.as_view(self, "config.json", lambda: self._config),
            r"/-/config<as_format:(\.json)?$>",
        )
        app.add_route(
            DatabaseDownload.as_view(self), r"/<db_name:[^/]+?><as_db:(\.db)$>"
        )
        app.add_route(
            DatabaseView.as_view(self), r"/<db_name:[^/]+?><as_format:(\.jsono?|\.csv)?$>"
        )
        app.add_route(
            TableView.as_view(self),
            r"/<db_name:[^/]+>/<table_and_format:[^/]+?$>",
        )
        app.add_route(
            RowView.as_view(self),
            r"/<db_name:[^/]+>/<table:[^/]+?>/<pk_path:[^/]+?><as_format:(\.jsono?)?$>",
        )
        self.register_custom_units()
        # On 404 with a trailing slash redirect to path without that slash:
        @app.middleware("response")
        def redirect_on_404_with_trailing_slash(request, original_response):
            if original_response.status == 404 and request.path.endswith("/"):
                path = request.path.rstrip("/")
                if request.query_string:
                    path = "{}?{}".format(path, request.query_string)
                return response.redirect(path)

        @app.exception(Exception)
        def on_exception(request, exception):
            title = None
            help = None
            if isinstance(exception, NotFound):
                status = 404
                info = {}
                message = exception.args[0]
            elif isinstance(exception, InvalidUsage):
                status = 405
                info = {}
                message = exception.args[0]
            elif isinstance(exception, DatasetteError):
                status = exception.status
                info = exception.error_dict
                message = exception.message
                if exception.messagge_is_html:
                    message = Markup(message)
                title = exception.title
            else:
                status = 500
                info = {}
                message = str(exception)
                traceback.print_exc()
            templates = ["500.html"]
            if status != 500:
                templates = ["{}.html".format(status)] + templates
            info.update(
                {"ok": False, "error": message, "status": status, "title": title}
            )
            if request is not None and request.path.split("?")[0].endswith(".json"):
                return response.json(info, status=status)

            else:
                template = self.jinja_env.select_template(templates)
                return response.html(template.render(info), status=status)

        return app
Esempio n. 23
0
import pymysql
import os
import sys
import json
import aiohttp
import importlib
import datetime

from math import trunc
from sanic import Sanic
from pytz import timezone
import sanic.response as response

from log_config import LOGGING_CONFIG

app = Sanic(__name__, log_config=LOGGING_CONFIG)
platform_name = ["Steam", "Kakao", "XBOX", "PS", "Stadia"]
platform_site = ["steam", "kakao", "xbox", "psn", "stadia"]
DB_platform = ["Steam", "Kakao", "XBOX", "PSN", "Stadia"]

directory = os.path.dirname(os.path.abspath(__file__)).replace("\\", "/")
db_f = open(f"{directory}/data/database.json", mode='r')
db = db_f.read()
db_f.close()
db_json = json.loads(db)

db_ip = db_json["mysql"]["ip"]
db_user = db_json["mysql"]["user"]
db_pw = db_json["mysql"]["password"]
db_name = db_json["mysql"]["database"]
Esempio n. 24
0
class WebServer:
    def __init__(
        self,
        contracting_client: ContractingClient,
        driver: ContractDriver,
        wallet,
        blocks,
        queue=[],
        port=8080,
        ssl_port=443,
        ssl_enabled=False,
        ssl_cert_file='~/.ssh/server.csr',
        ssl_key_file='~/.ssh/server.key',
        workers=2,
        debug=True,
        access_log=False,
        max_queue_len=10_000,
    ):

        # Setup base Sanic class and CORS
        self.app = Sanic(__name__)
        self.app.config.update({
            'REQUEST_MAX_SIZE': 10000,
            'REQUEST_TIMEOUT': 5,
            'KEEP_ALIVE': False,
        })
        self.cors = None

        # Initialize the backend data interfaces
        self.client = contracting_client
        self.driver = driver
        self.nonces = storage.NonceStorage()
        self.blocks = blocks

        self.static_headers = {}

        self.wallet = wallet
        self.queue = queue
        self.max_queue_len = max_queue_len

        self.port = port

        self.ssl_port = ssl_port
        self.ssl_enabled = ssl_enabled
        self.context = None

        # Create the SSL Context if needed
        if self.ssl_enabled:
            self.context = ssl.create_default_context(
                purpose=ssl.Purpose.CLIENT_AUTH)
            self.context.load_cert_chain(ssl_cert_file, keyfile=ssl_key_file)

        # Store other Sanic constants for when server starts
        self.workers = workers
        self.debug = debug
        self.access_log = access_log

        # Add Routes
        self.app.add_route(self.submit_transaction,
                           '/',
                           methods=['POST', 'OPTIONS'])
        self.app.add_route(self.ping, '/ping', methods=['GET', 'OPTIONS'])
        self.app.add_route(self.get_id, '/id', methods=['GET'])
        self.app.add_route(self.get_nonce, '/nonce/<vk>', methods=['GET'])

        # State Routes
        self.app.add_route(self.get_methods,
                           '/contracts/<contract>/methods',
                           methods=['GET'])
        self.app.add_route(self.get_variables,
                           '/contracts/<contract>/variables')
        self.app.add_route(self.get_variable,
                           '/contracts/<contract>/<variable>')
        self.app.add_route(self.get_contracts, '/contracts', methods=['GET'])
        self.app.add_route(self.get_contract,
                           '/contracts/<contract>',
                           methods=['GET'])
        self.app.add_route(self.get_constitution,
                           '/constitution',
                           methods=['GET'])
        #self.app.add_route(self.iterate_variable, '/contracts/<contract>/<variable>/iterate')

        # Latest Block Routes
        self.app.add_route(self.get_latest_block,
                           '/latest_block',
                           methods=[
                               'GET',
                               'OPTIONS',
                           ])
        self.app.add_route(self.get_latest_block_number,
                           '/latest_block_num',
                           methods=['GET'])
        self.app.add_route(self.get_latest_block_hash,
                           '/latest_block_hash',
                           methods=['GET'])

        # General Block Route
        self.app.add_route(self.get_block, '/blocks', methods=['GET'])

        # TX Route
        self.app.add_route(self.get_tx, '/tx', methods=['GET'])

        self.coroutine = None
Esempio n. 25
0
def test_app_name_required():
    with pytest.raises(SanicException):
        Sanic()
Esempio n. 26
0
def test_auto_load_env():
    environ["SANIC_TEST_ANSWER"] = "42"
    app = Sanic(name=__name__)
    assert app.config.TEST_ANSWER == 42
    del environ["SANIC_TEST_ANSWER"]
Esempio n. 27
0
def test_app_registry_retrieval():
    instance = Sanic("test")
    assert Sanic.get_app("test") is instance
Esempio n. 28
0
def test_auto_load_bool_env():
    environ["SANIC_TEST_ANSWER"] = "True"
    app = Sanic(name=__name__)
    assert app.config.TEST_ANSWER == True
    del environ["SANIC_TEST_ANSWER"]
Esempio n. 29
0
def test_get_app_default():
    instance = Sanic("test")
    assert Sanic.get_app() is instance
Esempio n. 30
0
def test_request_stream_app():
    '''for self.is_request_stream = True and decorators'''

    app = Sanic('test_request_stream_app')

    @app.get('/get')
    async def get(request):
        assert request.stream is None
        return text('GET')

    @app.head('/head')
    async def head(request):
        assert request.stream is None
        return text('HEAD')

    @app.delete('/delete')
    async def delete(request):
        assert request.stream is None
        return text('DELETE')

    @app.options('/options')
    async def options(request):
        assert request.stream is None
        return text('OPTIONS')

    @app.post('/_post/<id>')
    async def _post(request, id):
        assert request.stream is None
        return text('_POST')

    @app.post('/post/<id>', stream=True)
    async def post(request, id):
        assert isinstance(request.stream, asyncio.Queue)

        async def streaming(response):
            while True:
                body = await request.stream.get()
                if body is None:
                    break
                response.write(body.decode('utf-8'))
                request.stream.task_done()

        return stream(streaming)

    @app.put('/_put')
    async def _put(request):
        assert request.stream is None
        return text('_PUT')

    @app.put('/put', stream=True)
    async def put(request):
        assert isinstance(request.stream, asyncio.Queue)

        async def streaming(response):
            while True:
                body = await request.stream.get()
                if body is None:
                    break
                response.write(body.decode('utf-8'))
                request.stream.task_done()

        return stream(streaming)

    @app.patch('/_patch')
    async def _patch(request):
        assert request.stream is None
        return text('_PATCH')

    @app.patch('/patch', stream=True)
    async def patch(request):
        assert isinstance(request.stream, asyncio.Queue)

        async def streaming(response):
            while True:
                body = await request.stream.get()
                if body is None:
                    break
                response.write(body.decode('utf-8'))
                request.stream.task_done()

        return stream(streaming)

    assert app.is_request_stream is True

    request, response = app.test_client.get('/get')
    assert response.status == 200
    assert response.text == 'GET'

    request, response = app.test_client.head('/head')
    assert response.status == 200
    assert response.text == ''

    request, response = app.test_client.delete('/delete')
    assert response.status == 200
    assert response.text == 'DELETE'

    request, response = app.test_client.options('/options')
    assert response.status == 200
    assert response.text == 'OPTIONS'

    request, response = app.test_client.post('/_post/1', data=data)
    assert response.status == 200
    assert response.text == '_POST'

    request, response = app.test_client.post('/post/1', data=data)
    assert response.status == 200
    assert response.text == data

    request, response = app.test_client.put('/_put', data=data)
    assert response.status == 200
    assert response.text == '_PUT'

    request, response = app.test_client.put('/put', data=data)
    assert response.status == 200
    assert response.text == data

    request, response = app.test_client.patch('/_patch', data=data)
    assert response.status == 200
    assert response.text == '_PATCH'

    request, response = app.test_client.patch('/patch', data=data)
    assert response.status == 200
    assert response.text == data