def test_pickle_app_with_bp(app, protocol): from sanic import Blueprint bp = Blueprint("test_text") bp.route("/")(handler) app.blueprint(bp) p_app = pickle.dumps(app, protocol=protocol) up_p_app = pickle.loads(p_app) assert up_p_app request, response = app.test_client.get("/") assert app.is_request_stream is False assert response.text == "Hello"
from sanic import Blueprint from sanic import response conversations = Blueprint('conversations', url_prefix='/conversations') @conversations.route('/') async def home(request): return response.text(request.path)
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", "type": "integer",
# -*- coding: utf-8 -*- import json from sanic import response from sanic import Blueprint from .query import Query bp = Blueprint(__name__) TABLE_NAME = 'segments' query = Query(TABLE_NAME, key_type={'layer': int, 'id': int}) def jsonify(records): """ Parse asyncpg record response into JSON format """ # return [dict(r.items()) for r in records] rs = [dict(r.items()) for r in records] for r in rs: actions = r.get('actions') or "{}" r['actions'] = json.loads(actions) return rs @bp.route('', methods=['GET']) async def root_get(request): args = request.raw_args async with bp.pool.acquire() as connection: try: (_qy, values) = query.get(args) results = await connection.fetch(_qy, *values)
from sanic import Blueprint from sanic.log import logger from sanic.response import json from sanic_openapi import doc from utils import udumps from utils.dbconn import ( fetch_channels, fetch_data, fetch_nijibili, nijisanji_channels_data, parse_uuids_args, ) from utils.models import BiliChannelsModel, BiliScheduleModel nijibp = Blueprint("Nijisanji", "/nijisanji", strict_slashes=True) @nijibp.get("/live") @doc.summary("Live/Upcoming Nijisanji streams") @doc.description( "Fetch a list of live/upcoming streams from Nijisanji/VirtuaReal VTubers" ", updated every 2/4 minutes via cronjob.") @doc.consumes( doc.String( name="uids", description="Filter upcoming results with User ID " "(support multiple id separated by comma)", ), location="query", )
from sanic import Blueprint home = Blueprint("home_route", url_prefix="/")
return False def get_usb_config_from_redis(): try: redis_connection = redis_connect() config = redis_connection.get("CONFIG.LOCAL_STORAGE_CONTROLLER_SERVER") config = json.loads(config) usb_config = config["usb"] return usb_config except Exception as e: print(e) return False usb_blueprint = Blueprint('usb_blueprint', url_prefix='/usb') @usb_blueprint.route('/') def commands_root(request): return response.text("you are at the /usb url\n") @usb_blueprint.route("/remount", methods=["GET"]) def status(request): result = {"message": "failed"} try: usb_config = get_usb_config_from_redis() usb_storage = USBStorage(usb_config) time.sleep(3) result["message"] = "success"
from sanic import Blueprint from sanic.response import json from src.internal.entities.biz.serializers.doctor_serializer import DoctorSerializer, FOR_FILTER from src.internal.entities.biz.services.doctor_service import DoctorServiceImpl from src.internal.errors.common import NOT_AUTHORIZED, NOT_VALID_TOKEN, OK from src.internal.servers.http.answer import get_response from src.lib.utils.utls import get_payload doctors = Blueprint('doctors', url_prefix='/doctors') @doctors.route('/') def get_all_doctors(request): token = request.cookies.get('token') if not token: return json(get_response(NOT_AUTHORIZED[0], NOT_AUTHORIZED[1]), 401) payload = get_payload(token) if not payload: return json(get_response(NOT_VALID_TOKEN[0], NOT_VALID_TOKEN[1]), 401) doctors, err = DoctorServiceImpl.get_all() if err: return json(get_response(err[0], err[1]), 400) resp_data = [ DoctorSerializer().serialize(doctor, FOR_FILTER) for doctor in doctors ] return json(get_response(OK[0], OK[1], data=resp_data))
from sanic import Blueprint from sanic.request import Request from sanic.response import json from sanic.views import HTTPMethodView from sanic_openapi import doc from app.misc.models import UserRegistration from app.repositories.connections import MySQLConnection from app.repositories.user import UserRepository from app.services.user import UserService blueprint = Blueprint('signup-api', url_prefix='/signup') class UserSignupView(HTTPMethodView): repository = UserRepository(MySQLConnection) service = UserService(repository) @doc.summary('Register account') @doc.consumes( UserRegistration, location='body', content_type='application/json', required=True) @doc.produces({'success': bool}, description='the result of account registration', content_type='application/json') async def post(self, request: Request): await self.service.create(request.json) return json({ 'success': True })
import asyncio import time import datetime from sanic import Blueprint from sanic.response import json from aiomysql import create_pool loop = asyncio.get_event_loop() ad_blueprint = Blueprint("ad_blueprint", url_prefix="/ad") # ad_blueprint.config.update(dict(MYSQL=dict(host="172.16.1.251", port=3306, user='******', password='', db=''))) @ad_blueprint.listener('before_server_start') async def start_mysql(app, loop): ad_mysql_config = app.config.get("MYSQL") if not ad_mysql_config: raise RuntimeError("ad mysql config not empty.") _mysql = await create_pool(**ad_mysql_config) async def _query(sqlstr, args=None): async with _mysql.acquire() as conn: async with conn.cursor() as cur: final_str = cur.mogrify(sqlstr, args) print('mysql query [{}]'.format(final_str)) await cur.execute(final_str) value = await cur.fetchall() return value
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ------------------------------------------------------------------------------ import logging from sanic import Blueprint from sanic import response from rest_api.insurance_common import transaction from rest_api.workflow import general, security_messaging from rest_api.workflow.errors import ApiBadRequest, ApiInternalError CONTRACT_BP = Blueprint('contract') logging.basicConfig(level=logging.DEBUG) LOGGER = logging.getLogger(__name__) @CONTRACT_BP.get('contract') async def get_all_contacts(request): """Fetches complete details of all Accounts in state""" LOGGER.debug("Call 'contract' request") client_key = general.get_request_key_header(request) contract_list = await security_messaging.get_contracts(request.app.config.VAL_CONN, client_key) contract_list_json = [] for address, con in contract_list.items(): contract_list_json.append({ 'client_pkey': con.client_pkey,
data = tweet._json try: await cur.execute( core.INSERT_TWEET_QUERY, (data['id'], user_id, data['text'], data['created_at'], data['source'].split('>')[1].split('<')[0])) except IntegrityError: pass await con.commit() # -------------------------------------------------------------------------- Private -- # -- Blueprint -------------------------------------------------------------------------- root: Blueprint = Blueprint('root', None) @root.route('/get-user-info', {'GET', 'POST', 'OPTIONS'}) async def get_user_info(request: Request) -> HTTPResponse: screen_name, *_ = mzk.get_args( request, ('screen_name|name', str, None, { 'max_length': 32 }), ) if screen_name is None: raise Forbidden('screen_name parameter format error.') try: return json(await __get_info(request, screen_name)) except mzk.TweepError:
# coding:utf-8 """ HTTP API methods for Dagobah daemon. """ import json from src.bus.common.util import validate_dict from sanic import Blueprint from src.bus.func.api import api_call from sanic import response from io import StringIO bp_api = Blueprint('api') dagobah = '' @bp_api.listener('before_server_start') async def init_global_variable(app, loop): global dagobah dagobah = app.config['dagobah'] @bp_api.route('/api/jobs', methods=['GET']) @api_call async def get_jobs(request): return dagobah._serialize().get('jobs', {}) @bp_api.route('/api/job', methods=['GET']) @api_call async def get_job(request): args = dict(request.args) if not validate_dict(args, required=['job_name'], job_name=str): raise ValueError('not validate info')
from urllib.parse import parse_qs from sanic import Blueprint from sanic import response from dash.data.penguin import Penguin, ActivationKey from dash import env, app import aiohttp import i18n vanilla_activate = Blueprint('vanilla_activate', url_prefix='/activate/vanilla') @vanilla_activate.get('/<lang>/<code>') async def activate_page_autofill(_, lang, code): if lang == 'fr': register_template = env.get_template('activate/fr.html') page = register_template.render( VANILLA_PLAY_LINK=app.config.VANILLA_PLAY_LINK, site_key=app.config.GSITE_KEY, activation_key=code) return response.html(page) elif lang == 'es': register_template = env.get_template('activate/es.html') page = register_template.render( VANILLA_PLAY_LINK=app.config.VANILLA_PLAY_LINK, site_key=app.config.GSITE_KEY, activation_key=code) return response.html(page) elif lang == 'pt': register_template = env.get_template('activate/pt.html')
from sanic.response import json from sanic import Blueprint from sanic.views import HTTPMethodView from playhouse.shortcuts import model_to_dict from .models import ShanghaiPersonInfo from .helper import list_remove_repeat crud_bp = Blueprint( 'crud', url_prefix='/api/persons' ) class PersonsInfoListView(HTTPMethodView): """ @api {GET} /api/persons Get all or a part of person info @apiName GetAllInfoList @apiGroup Info Manage @apiVersion 1.0.0 @apiExample {httpie} Example usage: (support combinatorial search) All person: http /api/persons You can according to 'sex | email' or 'sex & email' http /api/persons?sex=xxx&email=xx http /api/persons?sex=xxx http /api/persons?email=xx
from sanic import Sanic from sanic.response import json as sanic_json import json import time import requests from beaker.cache import cache_regions, cache_region from sanic import Blueprint cache_regions.update({ 'memory': { 'expire': 600, 'type': 'memory' } }) bp = Blueprint('DashBoard', url_prefix='/DashBoard') def time_to_time_stamp(data): result = int(str(int(time.mktime(time.strptime(data, '%Y%m%d')))) + '000') return result @cache_region('memory') def get_target_and_target_data(): result = {} # 外网 url = 'http://34.214.222.244:12000/model-dashboard/monitor/report/days/14' # 内网 # url = 'http://172.31.23.134:12000/model-dashboard/monitor/report/days/14' data = requests.get(url)
import db import os import aiofiles import uuid import xlrd import hashlib import aiohttp from sanic.response import stream, text import zipfile import json as innerjson import time import signal from log_support import do_log from config import * bp_openstack = Blueprint('bp_openstack') #Monitor @bp_openstack.get("/teacher/monitor") async def get_userCourseOne(request): get_info = request.raw_args try: id = int(get_info['id']) info = await db_select("userTemplate", u_id=id) template_id = [] infoX = [] for item in info: #print(item['template']) if item['template'] == None or item['template'] == '': pass
from sanic.response import json from sanic import Blueprint from sanic.views import HTTPMethodView from playhouse.shortcuts import model_to_dict from .models import ShanghaiPersonInfo from .helper import list_remove_repeat crud_bp = Blueprint('crud', url_prefix='/api/persons') class PersonsInfoListView(HTTPMethodView): """ @api {GET} /api/persons Get all or a part of person info @apiName GetAllInfoList @apiGroup Info Manage @apiVersion 1.0.0 @apiExample {httpie} Example usage: (support combinatorial search) All person: http /api/persons You can according to 'sex | email' or 'sex & email' http /api/persons?sex=xxx&email=xx http /api/persons?sex=xxx http /api/persons?email=xx @apiParam {String} sex @apiParam {String} email
# -*- coding: utf-8 -*- # Created by apple on 2017/2/5. import os from ..log import log from ..config import Config from sqlalchemy import func, desc from sanic import Blueprint from sanic.request import Request from sanic.response import text from ..exceptions import BadRequest from ..utils import JsonResult, Regex, Date, DB from sanic.views import HTTPMethodView from ..db import Session, AppModel, AppVersionModel apps_blueprint = Blueprint('apps', 'apps') @apps_blueprint.route('/<app_type:iOS|android|all>/page/<page:int>', ['GET']) async def get_apps(request: Request, app_type: str, page: int): """ 获取app - uri[app类型(all/iOS/android)-app_type: str, 页码(从1起)-page: int], format[时间s-t: int] :param request: :return: """ time = Date.time2datetime(request.args.get('t')) if not time: raise BadRequest('') if page <= 0:
from rbac.server.db import roles_query from rbac.server.db import users_query from rbac.server.db.db_utils import create_connection from rbac.common.logs import get_default_logger from rbac.common.sawtooth import batcher from rbac.server.blockchain_transactions.user_transaction import create_delete_user_txns from rbac.server.blockchain_transactions.role_transaction import ( create_del_ownr_by_user_txns, create_del_admin_by_user_txns, create_del_mmbr_by_user_txns, ) LOGGER = get_default_logger(__name__) AES_KEY = os.getenv("AES_KEY") USERS_BP = Blueprint("users") @USERS_BP.get("api/users") @authorized() async def fetch_all_users(request): """Returns all users.""" head_block = await utils.get_request_block(request) start, limit = utils.get_request_paging_info(request) user_resources = await users_query.fetch_all_user_resources( request.app.config.DB_CONN, start, limit) return await utils.create_response( request.app.config.DB_CONN, request.url, user_resources, head_block,
import logging import os # web framework from sanic import Blueprint, response from sanic.exceptions import ServerError from sanic.request import Request from sanic.response import HTTPResponse from sanic.log import logger from sanic_openapi import doc # predictor from predict import Predict, PredictError # initialize app v1 = Blueprint('v1', url_prefix='/api/v1') # initialize predictor predictor = Predict(logger=logger) # define a lock to allow only one thread of processing lock = None # initialize the lock @v1.listener('before_server_start') async def init(sanic, loop): global lock lock = asyncio.Lock()
import base58 config = configparser.ConfigParser() config.read('config.ini') dsn = { "user": os.environ['POSTGRES_USER'], "password": os.environ['POSTGRES_PASSWORD'], "database": os.environ['POSTGRES_DB'], "host": config['DB']['host'], "port": config['DB']['port'], "sslmode": config['DB']['sslmode'], "target_session_attrs": config['DB']['target_session_attrs'] } cdms = Blueprint('cdms_v1', url_prefix='/cdms') class Cdms(HTTPMethodView): @staticmethod def get(request, cdm_id): data = get_cdm(cdm_id) return json(data, status=200) def get_cdm(cdm_id): conn = psycopg2.connect(**dsn) try: with conn: with conn.cursor() as cur: sql = """ SELECT c.recipient_hash, c.thread_hash FROM cdms c WHERE id='{cdm_id}'
def get_blueprints(): books_blue_print = Blueprint('books', url_prefix='/books') books_blue_print.add_route(BooksView.as_view(), '/') books_blue_print.add_route(BookView.as_view(), '/<book_id:int>') authors_blue_print = Blueprint('authors', url_prefix='/authors') authors_blue_print.add_route(AuthorsView.as_view(), '/') authors_blue_print.add_route(AuthorView.as_view(), '/<author_id:int>') publishers_blue_print = Blueprint('publishers', url_prefix='/publishers') publishers_blue_print.add_route(PublishersView.as_view(), '/') publishers_blue_print.add_route(PublisherView.as_view(), '/<publisher_id:int>') maintainance_blue_print = Blueprint('maintainance', url_prefix='/filldb') maintainance_blue_print.add_route(MaintainanceView.as_view(), '/') return books_blue_print, authors_blue_print, publishers_blue_print, maintainance_blue_print
def blueprint( self, on_new_message: Callable[[UserMessage], Awaitable[Any]]) -> Blueprint: slack_webhook = Blueprint("slack_webhook", __name__) @slack_webhook.route("/", methods=["GET"]) async def health(_: Request) -> HTTPResponse: return response.json({"status": "ok"}) @slack_webhook.route("/webhook", methods=["GET", "POST"]) async def webhook(request: Request) -> HTTPResponse: content_type = request.headers.get("content-type") # Slack API sends either a JSON-encoded or a URL-encoded body depending on the content if content_type == "application/json": # if JSON-encoded message is received output = request.json event = output.get("event", {}) user_message = event.get("text", "") sender_id = event.get("user", "") metadata = self.get_metadata(request) if "challenge" in output: return response.json(output.get("challenge")) elif self._is_user_message( output) and self._is_supported_channel( output, metadata): return await self.process_message( request, on_new_message, text=self._sanitize_user_message( user_message, metadata["users"]), sender_id=sender_id, metadata=metadata, ) else: logger.warning( f"Received message on unsupported channel: {metadata['out_channel']}" ) elif content_type == "application/x-www-form-urlencoded": # if URL-encoded message is received output = request.form payload = json.loads(output["payload"][0]) if self._is_interactive_message(payload): sender_id = payload["user"]["id"] text = self._get_interactive_response( payload["actions"][0]) if text is not None: metadata = self.get_metadata(request) return await self.process_message( request, on_new_message, text, sender_id, metadata) if payload["actions"][0]["type"] == "button": # link buttons don't have "value", don't send their clicks to bot return response.text("User clicked link button") return response.text( "The input message could not be processed.", status=500) return response.text("Bot message delivered.") return slack_webhook
def redis_connect(): try: redis_connection = redis.StrictRedis( host="127.0.0.1", port="6379", db=1, #password=ConfigDataBase.self[ 'redis' ][ 'password' ] ) return redis_connection except Exception as e: return False youtube_blueprint = Blueprint('youtube', url_prefix='/youtube') @youtube_blueprint.route('/') def commands_root(request): return response.text( "you are at the websitecontroller:11401/api/youtube url\n") @youtube_blueprint.route("/pause", methods=["GET"]) def pause(request): result = {"message": "failed"} try: time.sleep(1) result["status"] = "" result["message"] = "success"
from sanic import Blueprint from os import environ as env import re import json import uuid bot = InteractionBot( token=env["BOT_TOKEN"], public_key=env["BOT_PUBLIC_KEY"], guild_id=env.get("BOT_GUILD_ID"), ) db = None Format.ERROR.footer = "[Support](https://discord.club/discord) | [FAQ](https://discord.club/faq)" bp = Blueprint(name="api.bot", url_prefix="/entry") @bp.post("/") async def bot_entry(req): return await bot.sanic_entry(req) @bot.command() async def help(ctx): """ Information about Embed Generator and discord.club """ await ctx.respond( "**The best way to generate embeds and improve the look of your discord server!**\n", components=[ActionRow(
from rbac.common.user import User from rbac.common.role import Role from rbac.common.task import Task from rbac.common.logs import get_default_logger from rbac.server.api.errors import ApiBadRequest from rbac.server.api.auth import authorized from rbac.server.api import utils from rbac.server.db import proposals_query from rbac.server.db.relationships_query import fetch_relationships from rbac.server.db.users_query import fetch_user_resource from rbac.server.db.db_utils import create_connection LOGGER = get_default_logger(__name__) PROPOSALS_BP = Blueprint("proposals") TABLES = { "ADD_ROLE_TASK": "task_owners", "ADD_ROLE_MEMBER": "role_owners", "ADD_ROLE_OWNER": "role_admins", "ADD_ROLE_ADMIN": "role_admins", "REMOVE_ROLE_TASK": "task_owners", "REMOVE_ROLE_MEMBER": "role_owners", "REMOVE_ROLE_OWNER": "role_admins", "REMOVE_ROLE_ADMIN": "role_admins", "ADD_TASK_OWNER": "task_admins", "ADD_TASK_ADMIN": "task_admins", "REMOVE_TASK_OWNER": "task_admins", "REMOVE_TASK_ADMIN": "task_admins",
from sanic import Blueprint from ext import mako from models import Post bp = Blueprint('views') # 注册蓝图 @bp.route('/') # 路由:根目录 @mako.template('index.html') # 装饰器,async def 之上 async def index(request): name = request.args.get('title', 'World') # 拿参数,如果没有默认为World post = await Post.create(title=name) print(await Post.filter(title=name).first()) return {'post': post} # 返回的结果给template使用
from sanic import Blueprint from websockets.exceptions import ConnectionClosed from functools import wraps from util import decode_hyext_jwt from manager import ws_listener from logic.protocol import PROTOCOL from logic.game_packet import GamePacket from logger import log from sanic.response import json as response_json # 处理所有的 ws 请求 ws_bp = Blueprint('ws_blueprint', url_prefix='/ws') def jwt_authorized(): """ jwt认证装饰器 """ def decorator(f): @wraps(f) async def decorated_function(request, *args, **kwargs): payload = check_jwt_status(request) if payload: response = await f(request, payload, *args, **kwargs) return response else: return response_json({'status': 'not_authorized'}, 403) return decorated_function return decorator
from sanic import Blueprint from sanic.exceptions import ServerError, InvalidUsage from sanic.response import json bp_admin = Blueprint('admin') @bp_admin.route('/health', methods=["GET"]) async def bp_healthcheck(request): try: resp = {"STATUS": "Rock and Roll"} return json(resp) except TypeError as err: raise ServerError(str(err), status_code=400) except InvalidUsage as err: raise ServerError(str(err), status_code=400) except Exception as err: raise ServerError("Internal error.", status_code=500)
from sanic import Blueprint post_api = Blueprint('Posts', url_prefix='/posts', strict_slashes=True) __import__('server.api.posts.resources.posts')
from sanic import Blueprint from api.users.view import UsersView, GetUsersView users_routes = Blueprint('users_routes', url_prefix='/users', strict_slashes=True) users_routes.add_route(UsersView.as_view(), '') users_routes.add_route(GetUsersView.as_view(), '/<id>')
''' Copyright (C) 2020 Link Shortener Authors (see AUTHORS in Documentation). Licensed under the MIT (Expat) License (see LICENSE in Documentation). ''' from sanic import Blueprint from sanic.response import html, json, redirect template_blueprint = Blueprint('templates') @template_blueprint.route('/links/about') async def about_page(request): try: base = open('src/templates/base.html', 'r').read() about = open('src/templates/about/about.html', 'r').read() return html(base + about) except Exception as error: print(error) return json({'message': 'getting route failed'}, status=500) @template_blueprint.route('/', methods=['GET']) async def landing_page(request): return redirect('/links/about')