qs.execute() new_data = ShanghaiPersonInfo.get(id=item_id) return json(model_to_dict(new_data)) class SexListView(HTTPMethodView): """ @api {GET} /api/persons/sex Get all sexList @apiName GetAllSexList @apiGroup Info Manage @apiVersion 1.0.0 @apiExample {httpie} Example usage: http /api/persons/sex @apiSuccess {String} label @apiSuccess {String} value """ async def get(self, request): unique_list = list_remove_repeat(ShanghaiPersonInfo.values_list('sex')) result = [dict(label=i, value=i) for i in unique_list] return json(result) crud_bp.add_route(PersonsInfoDetailView.as_view(), '/detail/<item_id>') crud_bp.add_route(PersonsInfoListView.as_view(), '') crud_bp.add_route(SexListView.as_view(), '/sex')
# -*- coding:utf-8 -*- from sanic import Blueprint from sanic.request import Request from sanic.response import json from sanic.views import HTTPMethodView guomei_blueprint = Blueprint('guomei') class GoldData(HTTPMethodView): def __init__(self): super(GoldData, self).__init__() @staticmethod async def options(request: Request, app_id: int): return text('', headers={ 'Access-Control-Allow-Methods': 'GET,PUT,DELETE,OPTIONS', 'Access-Control-Max-Age:': '62400', }) @staticmethod async def get(request: Request): return json({'guomeihuangjin': '11223344'}) guomei_blueprint.add_route(GoldData.as_view(), '/guomei/gold')
class HitomiImagesInfoView(HTTPMethodView): async def get(self, request: HeliotropeRequest, index): if query_galleryinfo := await get_galleryinfo(index): files = HitomiImageModel.image_model_generator(query_galleryinfo["files"]) elif requested_galleryinfo := await request.app.ctx.hitomi_requester.get_galleryinfo( index ): files = HitomiImageModel.image_model_generator(requested_galleryinfo.files) else: return not_found return json( { "files": list( map( lambda file: { "name": file.name, "image": shuffle_image_url( image_url_from_image(int(index), file, True) ), }, files, ) ) } ) hitomi_images.add_route(HitomiImagesInfoView.as_view(), "/<index:int>")
def set_up_routes(app: Sanic): api = Blueprint('api', url_prefix='/api/v1') api.add_route(note.add, '/add', methods=('POST',)) api.add_route(note.edit, '/edit/<id:int>', methods=('POST',)) api.add_route(note.del_by_id, '/delete/<id:int>', methods=('DELETE',)) api.add_route(note.set_done, '/done/<id:int>', methods=('POST',)) api.add_route(note.set_undone, '/undone/<id:int>', methods=('POST',)) api.add_route(note.set_in_progress, '/in_progress/<id:int>', methods=('POST',)) api.add_route(note.set_off_progress, '/off_progress/<id:int>', methods=('POST',)) app.blueprint(api) app.blueprint(swagger_blueprint) app.add_route(ping.ping, '/ping', methods=('GET',)) return app
from sanic import Blueprint from service.v1.views.user_views import (UserHandlerView) from service.v1.views.task_views import (TaskHandlerView) # user user_bp = Blueprint('user') user_bp.add_route(UserHandlerView.as_view(), '/user') # task task_bp = Blueprint('task') user_bp.add_route(TaskHandlerView.as_view(), '/task') # group Blueprint api_blueprint_v1 = Blueprint.group(user_bp, task_bp)
from sanic.views import HTTPMethodView from zapier_fun.exceptions import ZapierException from zapier_fun.forms import IntroduceForm from zapier_fun.utils import call_webhook v1 = Blueprint('v1', url_prefix='/api/v1') class IntroduceView(HTTPMethodView): async def post(self, request): """Introduce yourself""" form = IntroduceForm.from_json(request.json) if not form.validate(): return json({"errors": form.errors}, status=400) try: response = await call_webhook(form) except ZapierException as e: abort( 500, "There was an issue calling the " "Zapier web hook: {0} {1}".format(type(e).__name__, e)) return json(response) v1.add_route(IntroduceView.as_view(), '/introduce')
#!/usr/bin/env python3 from sanic import Blueprint from views import AuthDescribe, AuthGetToken, AuthCreateRole bp = Blueprint('auth', '/auth') [ bp.add_route(handler, path) for handler, path in [ (AuthDescribe.as_view(), "/describe/<identifier_type>/<identifier>" ), # describe identifier (user_id / email / token) (AuthGetToken.as_view(), "/get_token/"), # verify identity and produce an access token (AuthCreateRole.as_view(), "/create_role/"), # create user ] ]
# -*- coding: utf-8 -*- from sanic import Sanic, Blueprint from sanic.views import HTTPMethodView from sanic.response import text blueprint = Blueprint('index', url_prefix='/') class Index(HTTPMethodView): async def get(self, request): return text('hello momo!') blueprint.add_route(Index.as_view(), '/')
def load_api(app: Sanic): api_v1 = Blueprint("v1", url_prefix=None) api_v1.add_route(UserDataView.as_view(), "/") app.blueprint(api_v1)
from sanic import Blueprint from .views import RegisterUserView user_bp = Blueprint('users', url_prefix='/users') user_bp.add_route(RegisterUserView.as_view(), '/register')
async def get(self, request): if not await oauth2_itsyouonline([]).check_token(request): return text('', 401) return await users_api.users_get(request) async def post(self, request): if not await oauth2_itsyouonline(["user:memberof:goraml-admin"]).check_token(request): return text('', 401) return await users_api.users_post(request) users_if.add_route(usersView.as_view(), '/users') class users_byusernameView(HTTPMethodView): async def get(self, request, username): if not await oauth2_itsyouonline(["user:memberof:goraml"]).check_token(request): return text('', 401) return await users_api.users_byUsername_get(request, username) users_if.add_route(users_byusernameView.as_view(), '/users/<username>')
from sanic import Blueprint from app.api.v4.users import get_all_users_method, update_user_by_id_method, add_user_method, get_user_by_id_method, \ delete_user_by_id_method api_v4_blueprint = Blueprint('api_v4', url_prefix='/v4') api_v4_blueprint.add_route(get_all_users_method, uri='/users', methods=['GET']) api_v4_blueprint.add_route(get_user_by_id_method, uri='/users/<user_id>', methods=['GET']) api_v4_blueprint.add_route(update_user_by_id_method, uri='/users/<user_id>', methods=['PUT']) api_v4_blueprint.add_route(add_user_method, uri='/users', methods=['POST']) api_v4_blueprint.add_route(delete_user_by_id_method, uri='/users/<user_id>', methods=['DELETE'])
from config import PRIVATE_KEY_PATH from config import UPLOAD_PATH, SUPPORT_TYPE from core.tool import ok, fail, checkParam, getMd5, rsaDecrypt from core.session import makeToken, checkToken, clearToken, updataToken from core.app import listView, itemView # from core.handle import middleHandle from core import rest FIX = PREFIX['be'] # 创建 蓝图 bp = Blueprint('be', url_prefix=FIX) # 加载默认 rest 接口生成路由 bp.add_route(listView.as_view(), '<name>') bp.add_route(itemView.as_view(), '<name>/<oid>') # @bp.middleware('request') # async def check(request): # rep = middleHandle(request, FIX, ANYAPI) # if rep: # return rep # 登录接口 @bp.route('login', methods=['POST']) async def login(request): dat = request.json manageData = {'username': '******', 'password': '******'} res = fail('参数错误', 400)
#!/usr/bin/env python3 """ This file is only for running sanic image test. Not included in prod image. """ from sanic import Blueprint from views.ddns_report import DDNSReportView from views.ddns_setup import DDNSSetupView bp = Blueprint('ddns', '/api/ddns') bp.add_route(DDNSReportView.as_view(), '/report/<secret_id>') bp.add_route(DDNSSetupView.as_view(), '/setup/<user_id>')
from sanic import Blueprint from sanic_graphql import GraphQLView # from server.resolvers import schema_test # from server.resolvers.user.user import user_schema from server.apis.grapql.resolvers.user import user_schema bp = Blueprint('graph', url_prefix='/graph') bp.add_route(GraphQLView.as_view(schema=user_schema, graphiql=True), '/graphql/user') bp.add_route(GraphQLView.as_view(schema=user_schema, batch=True), '/graphql/user/batch')
from sanic import Blueprint from . import views hello_bp = Blueprint("hello", strict_slashes=False) hello_bp.add_route( views.HelloView.as_view(), uri='/hello', methods=['GET'] )
validate_xml(StringIO(post_str)) return post_str def _decrypt_xml(self, params, crypt, xml_str): nonce = params.get('nonce') msg_sign = params.get('msg_signature') timestamp = params.get('timestamp') ret, decryp_xml = crypt.DecryptMsg(xml_str, msg_sign, timestamp, nonce) return decryp_xml, nonce def _encryp_xml(self, crypt, to_xml, nonce): to_xml = smart_str(to_xml) ret, encrypt_xml = crypt.EncryptMsg(to_xml, nonce) return encrypt_xml def post(self, request): args = self._get_args(request) weixin = WeixinMpAPI(**args) if not weixin.validate_signature(): raise AttributeError("Invalid weixin signature") xml_str = self._get_xml(request.body) crypt = WXBizMsgCrypt(token, encoding_aeskey, appid) decryp_xml, nonce = self._decrypt_xml(request.raw_args, crypt, xml_str) xml_dict = xmltodict.parse(decryp_xml) xml = WXResponse(xml_dict)() or 'success' encryp_xml = self._encryp_xml(crypt, xml, nonce) return text(encryp_xml or xml) blueprint.add_route(WXRequestView.as_view(), '/request')
from sanic import Blueprint from .device import DeviceView, DeviceNeighborView from .flow import FlowView from .flow_routing import FlowRoutingView from .link import LinkView from .neighbor import NeighborView from .path import PathView from .routing import RoutingView from .initialization import InitializationView api_v1 = Blueprint('link', url_prefix='/') api_v1.add_route(DeviceView.as_view(), '/device') api_v1.add_route(DeviceView.as_view(), '/device/mgmtip/<ip>') api_v1.add_route(DeviceView.as_view(), '/device/<device_id>') api_v1.add_route(DeviceNeighborView.as_view(), '/device/<device_id>/neighbor') api_v1.add_route(LinkView.as_view(), '/link') api_v1.add_route(LinkView.as_view(), '/link/<_id>') api_v1.add_route(PathView.as_view(), '/path/<src_dst>') api_v1.add_route(FlowView.as_view(), '/flow') api_v1.add_route(FlowRoutingView.as_view(), '/flow/routing') api_v1.add_route(FlowRoutingView.as_view(), '/flow/routing/<id>') api_v1.add_route(RoutingView.as_view(), '/routes') api_v1.add_route(RoutingView.as_view(), '/routes/<device_id>') api_v1.add_route(NeighborView.as_view(), '/neighbor/<device_id>')
client = ipfshttpclient.connect('/ip4/{0}/tcp/{1}'.format(config['ipfs']['host'], config['ipfs']['port'])) if not client: return bad_request('IPFS server can not be reached') dir_id = str(uuid.uuid4()) file_id = str(uuid.uuid4()) dir_path = './files/' + dir_id os.mkdir(dir_path) file_name = file_id + '.txt' file_path = dir_path + '/' + file_name with open(file_path, 'w') as f: f.write(data) with client: ipfs_data = client.add(file_path) os.remove(file_path) os.rmdir(dir_path) return ipfs_data def read_ipfs_file(ipfs_hash): data = requests.get('{0}/ipfs/{1}'.format(config['ipfs']['host'], ipfs_hash)).text return data ipfs.add_route(Ipfs.as_view(), '/') ipfs.add_route(Ipfs.as_view(), '/<ipfs_hash>')
instance = self.model.create( **data ) return json(model_to_dict(instance, exclude=[self.model.user.password])) class PostDetailView(HTTPMethodView): model = Post def get_object(self, id): try: instance = self.model.get(self.model.id == id) except self.model.DoesNotExist: return json({'data': 'NotFound'}, status=404) return instance async def get(self, request, id): instance = self.get_object(id) return json(model_to_dict(instance)) @class_login_required async def put(self, request, id): instance = self.get_object(id) update_model_from_dict(instance, request.json, ignore_unknown=True) instance.save() return json(model_to_dict(instance, exclude=[self.model.user.password])) post_bp.add_route(PostListView.as_view(), '/') post_bp.add_route(PostDetailView.as_view(), '/<id:number>')
tariff_json = list(filter(None, [ await request.app.loop.run_in_executor( request.app.thread_pool, lambda: TariffPrice(tariff_price_id).tariff ) for tariff_price_id in tariff_price_ids ])) tariff_results = len(tariff_json) reactive_energy_json = ReactiveEnergyPrice.create().reactiveEnergy tariff_json.append(reactive_energy_json) response = { 'count': tariff_results, 'data': tariff_json } response.update(links) return json(response) bp_tariff.add_route( TariffView.as_view(), '/tariff/', name='get_tariff', ) bp_tariff.add_route( TariffContractIdView.as_view(), '/tariff/<contractId>', name='get_tariff_by_contract_id', )
from sanic import Blueprint from api.company.view import CompanyView company_routes = Blueprint('company_routes', url_prefix='/CompanyProducts', strict_slashes=True) company_routes.add_route(CompanyView.as_view(), '')
from sanic import Blueprint from .user_source import UserView from .user_source.login_source import UserLoginView from .user_source.profile_source import UserProfileView apis = Blueprint('api', url_prefix='/api') apis.add_route(UserView.as_view(), '/user') apis.add_route(UserLoginView.as_view(), '/user/login') apis.add_route(UserProfileView.as_view(), '/user/profile')
async def put(self, request, id): pass async def patch(self, request, id): pass async def delete(self, request, id): pass class Xp(HTTPMethodView): async def get(self, request): return json({"Experience"}) async def post(self, request): pass async def put(self, request): pass async def patch(self, request): pass async def delete(self, request): pass xp_bp = Blueprint("xp", url_prefix="/api", version="v1") xp_bp.add_route(SingleXp.as_view(), "/xp/<id>") xp_bp.add_route(Xp.as_view(), "/xp")
from sanic import Blueprint from .views import dic_list, get_word, get_word_by_dic dic_bp_v1 = Blueprint('dictionary', url_prefix='/dictionary', version="v1") dic_bp_v1.add_route(dic_list, '/', methods=["GET"]) dic_bp_v1.add_route(get_word_by_dic, '/<dictionary_id:int>/word/<name:string>/', methods=["GET"]) dic_bp_v1.add_route(get_word, '/word/<name:string>', methods=["GET"])
return webJson(RetCode.PARAMETER_ERROR, data=("title exists")) logger.info("start to insert todo") await cur.execute(S.i_todo, (user_id, form.title, form.detail, form.created_time, form.updated_time)) await conn.commit() return webJson(data=form.title) def formatTodoInfo(data): """data是一个字典""" if data: data.created_time = datetime2str(data.created_time) data.updated_time = datetime2str(data.updated_time) return data return {} def formatTodosInfo(data): """data是一个列表""" if data: for i in range(len(data)): data[i] = formatTodoInfo(data[i]) return data return {} todo_bp.add_route(TodoListView.as_view(), '/') todo_bp.add_route(TodoView.as_view(), "/<todo_id:int>")
# -*- coding: utf-8 -*- from sanic import Blueprint from sanic.views import HTTPMethodView from sanic.response import text class Hello(HTTPMethodView): HELLO = "Hello World!" async def get(self, request): return text(Hello.HELLO) async def post(self, request): return text(Hello.HELLO) hello_bp = Blueprint("hello", url_prefix="/") hello_bp.add_route(Hello.as_view(), "hello")
heliotrope_image_proxy = Blueprint("heliotrope_image_proxy", url_prefix="/proxy") class HeliotropeImageProxyView(HTTPMethodView): async def get(self, request: HeliotropeRequest, shuffled_url: str): url = solve_shuffle_image_url(shuffled_url) if not url: return bad_request headers = { "referer": f"https://{request.app.ctx.hitomi_requester.domain}", "User-Agent": request.app.ctx.hitomi_requester.user_agent, } if "pximg" in url: headers.update({"referer": "https://pixiv.net"}) async with request.app.ctx.hitomi_requester.session.get( url, headers=headers) as r: if r.status != 200: return bad_request response = await request.respond(content_type=r.content_type) async for data, _ in r.content.iter_chunks(): await response.send(data) heliotrope_image_proxy.add_route(HeliotropeImageProxyView.as_view(), "/<shuffled_url>")
if script_type == 'test_scripts': root = await get_user_scripts_root(team=team, organization=organization) elif script_type == 'test_libraries': root = await get_back_scripts_root(team=team, organization=organization) else: return json(response_message(EINVAL, 'Unsupported script type ' + script_type)) if not await async_exists(root): await aiofiles.os.mkdir(root) for name, file in request.files.items(): if not is_path_secure(file.name): return json(response_message(EINVAL, 'saving file with an illegal file name')) found = True async with aiofiles.open(root / file.name, 'wb') as f: await f.write(file.body) if not found: return json(response_message(EINVAL, 'No files are found in the request')) if script_type == 'test_scripts': for name, file in request.files.items(): if not file.name.endswith('.md'): continue ret = await db_update_test(root, file.name, user, organization, team) if not ret: return json(response_message(UNKNOWN_ERROR, 'Failed to update test suite')) return json(response_message(SUCCESS)) bp.add_route(ScriptView.as_view(), '/')
from sanic import Blueprint, response from . import api_controller as ctr api = Blueprint('api', url_prefix='/api/') @api.middleware('request') async def check_headers(request): if request.headers['Content-Type'] != 'application/json': return response.json({'message': 'Unsupported Media Type'}, status=415) # @api.middleware('response') # async def cookies(request, response): # response.headers["Server"] = "Fake-Server" api.add_route(ctr.resize, 'resize', methods=['POST'])
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>')
from sanic import Blueprint from sanic.views import HTTPMethodView from sanic_jwt.decorators import protected from config import JINJA as jinja bp = Blueprint('home') class HomeView(HTTPMethodView): decorators = [protected()] async def get(self, request): return jinja.render('home.html', request) bp.add_route(HomeView.as_view(), '/home', name='home')