def on_app_start(self, app): # 定义jsonRpc框架 self.jsonrpc = JSONRPC( app, '/remoteCall', enable_web_browsable_api=True) self.on_regsiter_services(self.jsonrpc, session) self.on_regsiter_upload(self.app,self.jsonrpc)
def test_app_create_with_wrong_return(): app = Flask(__name__, instance_relative_config=True) jsonrpc = JSONRPC(app, '/api', enable_web_browsable_api=True) @jsonrpc.method('app.fn1') def fn2(s: str) -> Tuple[str, int, int, int]: # pylint: disable=W0612 return 'Bar {0}'.format(s), 1, 2, 3 with app.test_client() as client: rv = client.post('/api', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'app.fn1', 'params': [':)'] }) assert rv.json == { 'error': { 'code': -32000, 'data': { 'message': 'The view function did not return a valid ' 'response tuple. The tuple must have the form ' '(body, status, headers), (body, status), or ' '(body, headers).' }, 'message': 'Server error', 'name': 'ServerError', }, 'id': 1, 'jsonrpc': '2.0', } assert rv.status_code == 500
def test_app_create_with_method_without_annotation_on_params(): with pytest.raises(ValueError, match='no type annotations present to: app.fn2'): app = Flask(__name__, instance_relative_config=True) jsonrpc = JSONRPC(app, '/api', enable_web_browsable_api=True) # pylint: disable=W0612 @jsonrpc.method('app.fn4') def fn4(): pass # pylint: disable=W0612 @jsonrpc.method('app.fn2') def fn2(s) -> str: return 'Foo {0}'.format(s) # pylint: disable=W0612 @jsonrpc.method('app.fn1') def fn1(s: str) -> str: return 'Bar {0}'.format(s) # pylint: disable=W0612 @jsonrpc.method('app.fn3') def fn3(s): # pylint: disable=W0612 return 'Poo {0}'.format(s)
def test_app_create_with_method_without_annotation_on_return(): app = Flask(__name__, instance_relative_config=True) jsonrpc = JSONRPC(app, '/api', enable_web_browsable_api=True) # pylint: disable=W0612 @jsonrpc.method('app.fn1') def fn1(s: str): return 'Foo {0}'.format(s) # pylint: disable=W0612 @jsonrpc.method('app.fn2') def fn2(s: str) -> str: return 'Bar {0}'.format(s) with app.test_client() as client: rv = client.post('/api', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'app.fn1', 'params': [':)'] }) assert rv.json == { 'error': { 'code': -32602, 'data': { 'message': 'return type of str must be a type; got NoneType instead' }, 'message': 'Invalid params', 'name': 'InvalidParamsError', }, 'id': 1, 'jsonrpc': '2.0', } assert rv.status_code == 400 rv = client.post('/api', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'app.fn2', 'params': [':)'] }) assert rv.json == {'id': 1, 'jsonrpc': '2.0', 'result': 'Bar :)'} assert rv.status_code == 200
def test_app_create_without_register_app(): app = Flask(__name__, instance_relative_config=True) jsonrpc = JSONRPC(service_url='/api', enable_web_browsable_api=True) # pylint: disable=W0612 @jsonrpc.method('app.fn2') def fn1(s: str) -> str: return 'Foo {0}'.format(s) jsonrpc.init_app(app) with app.test_client() as client: rv = client.post('/api', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'app.fn2', 'params': [':)'] }) assert rv.json == {'id': 1, 'jsonrpc': '2.0', 'result': 'Foo :)'} assert rv.status_code == 200
def getJsonRpc(cls, *, web_app=_web_app, service_url='/api', enable_web_browsable_api=True): ''' the main flask json_rpc ''' if cls._json_rpc: return cls._json_rpc if web_app is None: return None cls._json_rpc = JSONRPC( app=web_app, service_url=service_url, enable_web_browsable_api=enable_web_browsable_api) logger.debug('Created web_app (Flask)') return cls._json_rpc
def init_jsonrpc(app, predictor): jsonrpc = JSONRPC(app, '/api', enable_web_browsable_api=True) @jsonrpc.method('PREDICTOR.predict') def predict(img_b64): """Get a prediction for the image tiles """ """Test: curl -i -X POST -H "Content-Type: application/json; indent=4" -d '{ "jsonrpc": "2.0", "method": "PREDICTOR.predict", "params": {"img_b64": "`base64 tst1.jpg`"}, "id": "1" }' http://localhost:5000/api """ print("PREDICT:") print("IMG: {}".format(img_b64)) if img_b64.startswith('data:'): # data:image/png;base64,... img_b64 = img_b64[img_b64.find(',')+1 : ] imgbytes = base64.b64decode(img_b64) # Image is bytes b'' img = skimage.io.imread(imgbytes, plugin='imageio') '''
def test_app_create_with_invalid_view_func(): app = Flask(__name__, instance_relative_config=True) jsonrpc = JSONRPC(app, service_url='/api', enable_web_browsable_api=True) # pylint: disable=W0612 @jsonrpc.method('app.fn2') def fn1(s: str) -> str: return 'Foo {0}'.format(s) with pytest.raises( ValueError, match='the view function must be either a function or a method'): jsonrpc.register(fn1.__new__, name='invalid') with app.test_client() as client: rv = client.post('/api', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'app.fn2', 'params': [':)'] }) assert rv.json == {'id': 1, 'jsonrpc': '2.0', 'result': 'Foo :)'} assert rv.status_code == 200
# -*- coding: utf-8 -*- import uuid import cPickle from flask_jsonrpc import JSONRPC from flask import Blueprint from captcha_server.ext.captcha import create_captcha from captcha_server.utils.words import lower_noblank from captcha_server.ext.cache import cache from flask import jsonify from captcha_server.ext.middleware import check_request captcha_rpc = Blueprint('catpcha_rpc', __name__) jsonrpc = JSONRPC(None, '/v1/rpc/captcha', enable_web_browsable_api=True) @jsonrpc.method('Captcha.example') def example(): return u'Welcome to Acttao Captcha Server!' @jsonrpc.method('Captcha.create') #@check_request() def create(chars=None): img, body, chars = create_captcha(chars) uid = unicode(uuid.uuid4()) cache.set(uid, cPickle.dumps({chars: body})) return jsonify(dict(code=10000, uid=uid, img=body)) @jsonrpc.method('Captcha.check')
def test_app_create_with_rcp_batch(): app = Flask(__name__, instance_relative_config=True) jsonrpc = JSONRPC(app, '/api', enable_web_browsable_api=True) # pylint: disable=W0612 @jsonrpc.method('sum') def sum_(a: int, b: int) -> int: return a + b # pylint: disable=W0612 @jsonrpc.method('subtract') def subtract(a: int, b: int) -> int: return a - b # pylint: disable=W0612 @jsonrpc.method('get_user') def get_user(uid: str) -> Dict[str, Any]: return {'uid': uid, 'name': 'John Dee'} # pylint: disable=W0612 @jsonrpc.method('notify_sum') def notify_sum(numbers: List[int]) -> int: s = sum([x**2 for x in numbers]) return s # pylint: disable=W0612 @jsonrpc.method('headers1') def headers1() -> Tuple[float, int, List[Tuple[str, Any]]]: return 3.141592653589793, 200, [('X-Header-1-a', 'a1'), ('X-Header-1-b', 'b1')] # pylint: disable=W0612 @jsonrpc.method('headers2') def headers2() -> Tuple[float, int, Tuple[str, Any]]: return 3.141592653589793, 201, ('X-Header-2-a', 'a2') # pylint: disable=W0612 @jsonrpc.method('headers3') def headers3() -> Tuple[float, int, Headers]: headers = Headers() headers.set('X-Header-3-a', 'a3') headers.set('X-Header-3-b', 'b3') headers.set('X-Header-3-c', 'c3') return 3.141592653589793, 200, headers # pylint: disable=W0612 @jsonrpc.method('headers4') def headers4() -> Tuple[float, int, Dict[str, Any]]: return 3.141592653589793, 200, { 'X-Header-4-a': 'a4', 'X-Header-4-b': 'b4' } # pylint: disable=W0612 @jsonrpc.method('headers_duplicate') def headers_duplicate() -> Tuple[float, int, Dict[str, Any]]: return ( 3.141592653589793, 400, { 'X-Header-2-a': 'a2-replaced', 'X-Header-4-b': 'b4-replaced', 'X-Header-3-c': 'c3-replaced', 'X-Header-1-a': 'a1-replaced', }, ) with app.test_client() as client: idx = uuid.uuid4() rv = client.post('/api', json={ 'id': idx.hex, 'jsonrpc': '2.0', 'method': 'sum', 'params': [1, 1] }) assert rv.json == {'id': idx.hex, 'jsonrpc': '2.0', 'result': 2} assert rv.status_code == 200 rv = client.post('/api', json=[]) assert rv.json == { 'error': { 'code': -32600, 'data': { 'message': 'Empty array' }, 'message': 'Invalid Request', 'name': 'InvalidRequestError', }, 'id': None, 'jsonrpc': '2.0', } assert rv.status_code == 400 rv = client.post('/api', json=[1]) assert rv.json == [{ 'error': { 'code': -32600, 'data': { 'message': 'Invalid JSON: 1' }, 'message': 'Invalid Request', 'name': 'InvalidRequestError', }, 'id': None, 'jsonrpc': '2.0', }] assert rv.status_code == 200 rv = client.post('/api', json=[1, 2, 3]) assert rv.json == [ { 'error': { 'code': -32600, 'data': { 'message': 'Invalid JSON: 1' }, 'message': 'Invalid Request', 'name': 'InvalidRequestError', }, 'id': None, 'jsonrpc': '2.0', }, { 'error': { 'code': -32600, 'data': { 'message': 'Invalid JSON: 2' }, 'message': 'Invalid Request', 'name': 'InvalidRequestError', }, 'id': None, 'jsonrpc': '2.0', }, { 'error': { 'code': -32600, 'data': { 'message': 'Invalid JSON: 3' }, 'message': 'Invalid Request', 'name': 'InvalidRequestError', }, 'id': None, 'jsonrpc': '2.0', }, ] assert rv.status_code == 200 rv = client.post( '/api', json=[ { 'id': '1', 'jsonrpc': '2.0', 'method': 'sum', 'params': [1, 1] }, { 'id': '2', 'jsonrpc': '2.0', 'method': 'subtract', 'params': [2, 2] }, { 'id': '3', 'jsonrpc': '2.0', 'method': 'sum', 'params': [3, 3] }, { 'id': '4', 'jsonrpc': '2.0', 'method': 'headers1' }, ], ) assert rv.json == [ { 'id': '1', 'jsonrpc': '2.0', 'result': 2 }, { 'id': '2', 'jsonrpc': '2.0', 'result': 0 }, { 'id': '3', 'jsonrpc': '2.0', 'result': 6 }, { 'id': '4', 'jsonrpc': '2.0', 'result': 3.141592653589793 }, ] assert rv.status_code == 200 assert len(rv.headers) == 4 assert 'Content-Type' in rv.headers assert 'Content-Length' in rv.headers assert rv.headers.get('X-Header-1-a') == 'a1' assert rv.headers.get('X-Header-1-b') == 'b1' rv = client.post( '/api', json=[ { 'id': '1', 'jsonrpc': '2.0', 'method': 'sum', 'params': [1, 1] }, { 'id': '2', 'jsonrpc': '2.0', 'method': 'subtract', 'params': [2, 2] }, { 'id': '3', 'jsonrpc': '2.0', 'method': 'get_user', 'params': { 'uid': '345' } }, { 'jsonrpc': '2.0', 'method': 'notify_sum', 'params': [[1, 2, 3, 4, 5]] }, { 'id': 'h1', 'jsonrpc': '2.0', 'method': 'headers1' }, { 'id': 'h2', 'jsonrpc': '2.0', 'method': 'headers2' }, { 'id': 'h3', 'jsonrpc': '2.0', 'method': 'headers3' }, { 'id': 'h4', 'jsonrpc': '2.0', 'method': 'headers4' }, ], ) assert rv.json == [ { 'id': '1', 'jsonrpc': '2.0', 'result': 2 }, { 'id': '2', 'jsonrpc': '2.0', 'result': 0 }, { 'id': '3', 'jsonrpc': '2.0', 'result': { 'uid': '345', 'name': 'John Dee' } }, { 'id': 'h1', 'jsonrpc': '2.0', 'result': 3.141592653589793 }, { 'id': 'h2', 'jsonrpc': '2.0', 'result': 3.141592653589793 }, { 'id': 'h3', 'jsonrpc': '2.0', 'result': 3.141592653589793 }, { 'id': 'h4', 'jsonrpc': '2.0', 'result': 3.141592653589793 }, ] assert rv.status_code == 200 assert len(rv.headers) == 10 assert 'Content-Type' in rv.headers assert 'Content-Length' in rv.headers assert rv.headers.get('X-Header-1-a') == 'a1' assert rv.headers.get('X-Header-1-b') == 'b1' assert rv.headers.get('X-Header-2-a') == 'a2' assert rv.headers.get('X-Header-3-a') == 'a3' assert rv.headers.get('X-Header-3-b') == 'b3' assert rv.headers.get('X-Header-3-c') == 'c3' assert rv.headers.get('X-Header-4-a') == 'a4' assert rv.headers.get('X-Header-4-b') == 'b4' rv = client.post( '/api', json=[ { 'jsonrpc': '2.0', 'method': 'notify_sum', 'params': [[1, 2, 3, 4, 5]] }, { 'jsonrpc': '2.0', 'method': 'notify_sum', 'params': [[1, 2, 3, 4, 5]] }, { 'jsonrpc': '2.0', 'method': 'notify_sum', 'params': [[1, 2, 3, 4, 5]] }, ], ) assert rv.json is None assert rv.status_code == 204 rv = client.post( '/api', json=[ { 'id': '1', 'jsonrpc': '2.0', 'method': 'sum', 'params': [1, 1] }, 1, { 'id': '2', 'jsonrpc': '2.0', 'method': 'subtract', 'params': [2, 2] }, { 'id': 'h1', 'jsonrpc': '2.0', 'method': 'headers1' }, { 'id': 'h2', 'jsonrpc': '2.0', 'method': 'headers2' }, { 'id': 'h3', 'jsonrpc': '2.0', 'method': 'headers3' }, { 'id': 'h4', 'jsonrpc': '2.0', 'method': 'headers4' }, { 'id': 'h_duplicate', 'jsonrpc': '2.0', 'method': 'headers_duplicate' }, ], ) assert rv.json == [ { 'id': '1', 'jsonrpc': '2.0', 'result': 2 }, { 'error': { 'code': -32600, 'data': { 'message': 'Invalid JSON: 1' }, 'message': 'Invalid Request', 'name': 'InvalidRequestError', }, 'id': None, 'jsonrpc': '2.0', }, { 'id': '2', 'jsonrpc': '2.0', 'result': 0 }, { 'id': 'h1', 'jsonrpc': '2.0', 'result': 3.141592653589793 }, { 'id': 'h2', 'jsonrpc': '2.0', 'result': 3.141592653589793 }, { 'id': 'h3', 'jsonrpc': '2.0', 'result': 3.141592653589793 }, { 'id': 'h4', 'jsonrpc': '2.0', 'result': 3.141592653589793 }, { 'id': 'h_duplicate', 'jsonrpc': '2.0', 'result': 3.141592653589793 }, ] assert rv.status_code == 200 assert len(rv.headers) == 10 assert 'Content-Type' in rv.headers assert 'Content-Length' in rv.headers assert rv.headers.get('X-Header-1-a') == 'a1-replaced' assert rv.headers.get('X-Header-1-b') == 'b1' assert rv.headers.get('X-Header-2-a') == 'a2-replaced' assert rv.headers.get('X-Header-3-a') == 'a3' assert rv.headers.get('X-Header-3-b') == 'b3' assert rv.headers.get('X-Header-3-c') == 'c3-replaced' assert rv.headers.get('X-Header-4-a') == 'a4' assert rv.headers.get('X-Header-4-b') == 'b4-replaced'
from flask import Flask PROJECT_DIR, PROJECT_MODULE_NAME = os.path.split( os.path.dirname(os.path.realpath(__file__))) FLASK_JSONRPC_PROJECT_DIR = os.path.join(PROJECT_DIR, os.pardir) if os.path.exists(FLASK_JSONRPC_PROJECT_DIR) \ and not FLASK_JSONRPC_PROJECT_DIR in sys.path: sys.path.append(FLASK_JSONRPC_PROJECT_DIR) from flask_jsonrpc import JSONRPC from flask_jsonrpc.site import JSONRPCSite app = Flask(__name__) jsonrpc_v1 = JSONRPC(app, '/api/v1', site=JSONRPCSite(), enable_web_browsable_api=True) jsonrpc_v2 = JSONRPC(app, '/api/v2', site=JSONRPCSite(), enable_web_browsable_api=True) @jsonrpc_v1.method('App.index') def index_v1(): return u'Welcome to Flask JSON-RPC Version API 1' @jsonrpc_v2.method('App.index') def index_v2(): return u'Welcome to Flask JSON-RPC Version API 2'
def create_app(test_config=None): # noqa: C901 pylint: disable=W0612 """Create and configure an instance of the Flask application.""" app = Flask(__name__, instance_relative_config=True) if test_config: app.config.update(test_config) jsonrpc = JSONRPC(app, '/api', enable_web_browsable_api=True) # pylint: disable=W0612 @jsonrpc.method('jsonrpc.greeting') def greeting(name: str = 'Flask JSON-RPC') -> str: return 'Hello {0}'.format(name) # pylint: disable=W0612 @jsonrpc.method('jsonrpc.echo') def echo(string: str, _some: Any = None) -> str: return string # pylint: disable=W0612 @jsonrpc.method('jsonrpc.notify') def notify(_string: str = None) -> None: pass # pylint: disable=W0612 @jsonrpc.method('jsonrpc.fails') def fails(n: int) -> int: if n % 2 == 0: return n raise ValueError('number is odd') # pylint: disable=W0612 @jsonrpc.method('jsonrpc.strangeEcho') def strangeEcho(string: str, omg: Dict[str, Any], wtf: List[str], nowai: int, yeswai: str = 'Default') -> List[Any]: return [string, omg, wtf, nowai, yeswai] # pylint: disable=W0612 @jsonrpc.method('jsonrpc.sum') def sum_(a: Union[int, float], b: Union[int, float]) -> Union[int, float]: return a + b # pylint: disable=W0612 @jsonrpc.method('jsonrpc.decorators') @jsonrcp_decorator def decorators(string: str) -> str: return 'Hello {0}'.format(string) # pylint: disable=W0612 @jsonrpc.method('jsonrpc.returnStatusCode') def return_status_code(s: str) -> Tuple[str, int]: return 'Status Code {0}'.format(s), 201 # pylint: disable=W0612 @jsonrpc.method('jsonrpc.returnHeaders') def return_headers(s: str) -> Tuple[str, Dict[str, Any]]: return 'Headers {0}'.format(s), {'X-JSONRPC': '1'} # pylint: disable=W0612 @jsonrpc.method('jsonrpc.returnStatusCodeAndHeaders') def return_status_code_and_headers( s: str) -> Tuple[str, int, Dict[str, Any]]: return 'Status Code and Headers {0}'.format(s), 400, {'X-JSONRPC': '1'} return app
from flask import Flask from flask_jsonrpc import JSONRPC from flask import make_response import requests import json import sqlite3 app = Flask(__name__) jsonrpc = JSONRPC(app, '/') @app.route('/check') def check(): return make_response('server online', 200) @jsonrpc.method('select_sql') def select_sql(sql): conn = sqlite3.connect("testing_db.sql3") cursor = conn.cursor() cursor.execute(sql) response_result = cursor.fetchall() cursor.close() conn.commit() conn.close() return response_result
db = SQLAlchemy() # redis链接对象 redis = FlaskRedis() # Session存储对象 session_store = Session() # 数据迁移实例对象 migrate = Migrate() # 日志对象 log = Log() # jsonrpc模块实例化对象 jsonrpc = JSONRPC(service_url="/api") # 数据转换器的对象创建 ma = Marshmallow() # jwt认证模块实例化 jwt = JWTManager() # flask-admin模块实例化 admin = Admin() # flask-babelex模块实例化 babel = Babel() # mongodb模块初始化 mongo = PyMongo()
from flask import Flask, request from flask_jsonrpc import JSONRPC from proxy.state import State from channel_manager.state import ChannelAddress from exception import ChannelDBAddFail from channel_manager import manager from flask_cors import CORS app = Flask(__name__) CORS(app, support_credentials=True) jsonrpc = JSONRPC(app, "/") @jsonrpc.method("registeaddress") def regist_address(address, port = "20556"): ip_info = request.headers.getlist("X-Forwarded-For")[0] if request.headers.getlist("X-Forwarded-For") else request.remote_addr channel_address = ChannelAddress() try: channel_address.add_address(address, ip=ip_info, port= port) except ChannelDBAddFail: channel_address.delete_address(address) return State.raise_fail(101, "Can Not Add The Address") return State.success() @jsonrpc.method("registchannle") def regist_channle(sender_addr, receiver_addr, asset_type,deposit, open_blockchain): return manager.regist_channel(sender_addr, receiver_addr, asset_type,deposit, open_blockchain)
# Rate Limiting limiter = Limiter(auto_check=True, key_func=get_remote_address) # CORS cors = CORS() # Session session = Session() # Flask-Allows allows = Allows(identity_loader=lambda: g.user) # Flask-RESTful api = Api() # Flask-Debugtoolbar toolbar = DebugToolbarExtension() # Flask-Babel babel = Babel() # Flask-Gzip gzip = Gzip(compress_level=9) # user service jsonrpc_user = JSONRPC(None, '/user') # message service jsonrpc_message = JSONRPC(None, '/message')
def test_app_create_modular_apps(): jsonrpc_api_1 = JSONRPCBlueprint('jsonrpc_api_1', __name__) # pylint: disable=W0612 @jsonrpc_api_1.method('blue1.fn2') def fn1_b1(s: str) -> str: return 'b1: Foo {0}'.format(s) jsonrpc_api_2 = JSONRPCBlueprint('jsonrpc_api_2', __name__) # pylint: disable=W0612 @jsonrpc_api_2.method('blue2.fn2') def fn1_b2(s: str) -> str: return 'b2: Foo {0}'.format(s) # pylint: disable=W0612 @jsonrpc_api_2.method('blue2.fn1') def fn2_b2(s: str) -> str: return 'b2: Bar {0}'.format(s) jsonrpc_api_3 = JSONRPCBlueprint('jsonrpc_api_3', __name__) # pylint: disable=W0612 @jsonrpc_api_3.method('blue3.fn2') def fn1_b3(s: str) -> str: return 'b3: Foo {0}'.format(s) app = Flask(__name__, instance_relative_config=True) jsonrpc = JSONRPC(app, '/api', enable_web_browsable_api=True) jsonrpc.register_blueprint(app, jsonrpc_api_1, url_prefix='/b1') jsonrpc.register_blueprint(app, jsonrpc_api_2, url_prefix='/b2') jsonrpc.register_blueprint(app, jsonrpc_api_3, url_prefix='/b3') with app.test_client() as client: rv = client.post('/api/b1', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'blue1.fn2', 'params': [':)'] }) assert rv.json == {'id': 1, 'jsonrpc': '2.0', 'result': 'b1: Foo :)'} assert rv.status_code == 200 rv = client.post('/api/b2', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'blue2.fn2', 'params': [':)'] }) assert rv.json == {'id': 1, 'jsonrpc': '2.0', 'result': 'b2: Foo :)'} assert rv.status_code == 200 rv = client.post('/api/b2', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'blue2.fn1', 'params': [':)'] }) assert rv.json == {'id': 1, 'jsonrpc': '2.0', 'result': 'b2: Bar :)'} assert rv.status_code == 200 rv = client.post('/api/b3', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'blue3.fn2', 'params': [':)'] }) assert rv.json == {'id': 1, 'jsonrpc': '2.0', 'result': 'b3: Foo :)'} assert rv.status_code == 200
from mesService import create_app from flask_jsonrpc import JSONRPC from mesService import config # from flask_uwsgi_websocket import GeventWebSocket # from flask_uwsgi_websocket import WebSocket from flask import request from mesService.lib.redisLib.RedisHelper import RedisHelper from mesService.modules.AngularInterface.websocket_service import ws_blue app = create_app(config.CURRENT_ENV) # ws = WebSocket(app) # ws.register_blueprint(ws_blue) # jsonrpc jsonrpc = JSONRPC(app, '/rpc/v1') import mesService.modules.AngularInterface.callrpc # 实现rpc接口 @app.after_request def after_request(response): """ Post request processing - add CORS, cache control headers """ # Enable CORS requests for local development # The following will allow the local angular-cli development environment to # make requests to this server (otherwise, you will get 403s due to same- # origin poly) response.headers.add('Access-Control-Allow-Origin', "*")
from coremodules.main import Run, Rescute UPLOAD_FOLDER = '/mnt/img/uploads' ALLOWED_EXTENSIONS = set(['img', 'zip']) app = Flask(__name__, static_url_path='/static') app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS jsonrpcRpiJson = JSONRPC(app, '/api/v1/rpiJson', site=JSONRPCSite(), enable_web_browsable_api=True) jsonrpcLogin = JSONRPC(app, '/api/v1/login', site=JSONRPCSite(), enable_web_browsable_api=True) jsonrpcRegister = JSONRPC(app, '/api/v1/register', site=JSONRPCSite(), enable_web_browsable_api=True) jsonrpcDeploy = JSONRPC(app, '/api/v1/deploy', site=JSONRPCSite(), enable_web_browsable_api=True) jsonrpcRescute = JSONRPC(app, '/api/v1/rescute',
return mongo.db.token.find_one({ 'token': token, 'expires_at': { '$gt': time.time() } }) is not None return True def dispatch(self, req_json): if not self.check_auth(req_json): raise JSONRPCError(message='Unauthorized', data={'message': 'Unauthorized'}) return super(AuthorizationSite, self).dispatch(req_json) jsonrpc = JSONRPC(None, '/api') jsonrpc_bp = JSONRPCBlueprint('blueprint', __name__, jsonrpc_site=AuthorizationSite) def after_request(response): # 允许跨域请求 response.headers['Access-Control-Allow-Origin'] = '*' response.headers[ 'Access-Control-Allow-Headers'] = 'Content-Type,X-Password' response.headers['Access-Control-Max-Age'] = 3600 return response def create_app(config_obj):
args = args[2:] except IndexError: if 'username' in kwargs and 'password' in kwargs: is_auth = f_check_auth(kwargs['username'], kwargs['password']) if is_auth: kwargs.pop('username') kwargs.pop('password') else: raise InvalidParamsError('Authenticated methods require at least ' '[username, password] or {username: password:} arguments') if not is_auth: raise InvalidCredentialsError() return f(*args, **kwargs) return _f jsonrpc = JSONRPC(app, '/api', auth_backend=authenticate) def check_auth(username, password): return True @jsonrpc.method('App.index', authenticated=check_auth) def index(): return 'Welcome to Flask JSON-RPC' @jsonrpc.method('App.echo(name=str)', authenticated=check_auth) def echo(name=''): return 'Hello {}'.format(name) if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)
import flaskweb.config as config app = Flask(__name__) app.secret_key = config.get('FLASK_SECRET_KEY') app.redis = config.get('REDIS_URL') app.config['SESSION_TYPE'] = 'redis' app.config['SESSION_REDIS'] = app.redis app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024 app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif'] app.config['UPLOAD_FOLDER'] = 'uploads' app.db_session = scoped_session(SessionLocal, scopefunc=_app_ctx_stack.__ident_func__) jsonrpc = JSONRPC(app, '/api', enable_web_browsable_api=True, jsonrpc_site_api=AuthorizationView) jsonrpc.register_blueprint(app, modules, url_prefix='/index', enable_web_browsable_api=True) jsonrpc.register_blueprint(app, auth, url_prefix='/auth', enable_web_browsable_api=True) @app.before_request def before_request(): if 'identifier' not in session: session['identifier'] = str(uuid.uuid4())
def test_app_create_multiple_jsonrpc_versions(): app = Flask(__name__, instance_relative_config=True) jsonrpc_v1 = JSONRPC(app, '/api/v1', enable_web_browsable_api=True) jsonrpc_v2 = JSONRPC(app, '/api/v2', enable_web_browsable_api=True) # pylint: disable=W0612 @jsonrpc_v1.method('app.fn2') def fn1_v1(s: str) -> str: return 'v1: Foo {0}'.format(s) # pylint: disable=W0612 @jsonrpc_v2.method('app.fn2') def fn1_v2(s: str) -> str: return 'v2: Foo {0}'.format(s) # pylint: disable=W0612 @jsonrpc_v1.method('app.fn3') def fn3(s: str) -> str: return 'Poo {0}'.format(s) # pylint: disable=W0612 @jsonrpc_v2.method('app.fn1') def fn2(s: str) -> str: return 'Bar {0}'.format(s) with app.test_client() as client: rv = client.post('/api/v1', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'app.fn2', 'params': [':)'] }) assert rv.json == {'id': 1, 'jsonrpc': '2.0', 'result': 'v1: Foo :)'} assert rv.status_code == 200 rv = client.post('/api/v2', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'app.fn2', 'params': [':D'] }) assert rv.json == {'id': 1, 'jsonrpc': '2.0', 'result': 'v2: Foo :D'} assert rv.status_code == 200 rv = client.post('/api/v1', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'app.fn3', 'params': [';)'] }) assert rv.json == {'id': 1, 'jsonrpc': '2.0', 'result': 'Poo ;)'} assert rv.status_code == 200 rv = client.post('/api/v2', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'app.fn1', 'params': ['\\oB'] }) assert rv.json == {'id': 1, 'jsonrpc': '2.0', 'result': 'Bar \\oB'} assert rv.status_code == 200
# coding=utf-8 from flask import Flask from flask_session import Session from flask_sqlalchemy import SQLAlchemy from .settings.dev import DevConfig from .settings.prod import ProdConfig from .utils.log import setup_log from .utils.helper import get_redis_connection from flask_script import Manager, Command from flask_migrate import Migrate, MigrateCommand from flask_jsonrpc import JSONRPC from flask_jsonrpc.site import JSONRPCSite from flask_admin import Admin jsonrpc_v1 = JSONRPC(app=None, service_url='/api/v1', site=JSONRPCSite(), enable_web_browsable_api=True) jsonrpc_v2 = JSONRPC(app=None, service_url='/api/v2', site=JSONRPCSite(), enable_web_browsable_api=True) config = { "dev": DevConfig, "prop": ProdConfig, } # 创建数据库链接对象 db = SQLAlchemy()
def test_app_create(): app = Flask(__name__, instance_relative_config=True) jsonrpc = JSONRPC(app, '/api', enable_web_browsable_api=True) # pylint: disable=W0612 @jsonrpc.method('App.index') def index() -> str: return 'Welcome to Flask JSON-RPC' # pylint: disable=W0612 @jsonrpc.method('app.fn0') def fn0(): pass # pylint: disable=W0612 @jsonrpc.method('app.fn1') def fn1() -> str: return 'Bar' # pylint: disable=W0612 @jsonrpc.method('app.fn2') def fn2(s: str) -> str: return 'Foo {0}'.format(s) with app.test_client() as client: rv = client.post('/api', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'App.index', 'params': [] }) assert rv.json == { 'id': 1, 'jsonrpc': '2.0', 'result': 'Welcome to Flask JSON-RPC' } assert rv.status_code == 200 rv = client.post('/api', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'app.fn0', 'params': [] }) assert rv.json == {'id': 1, 'jsonrpc': '2.0', 'result': None} assert rv.status_code == 200 rv = client.post('/api', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'app.fn1', 'params': [] }) assert rv.json == {'id': 1, 'jsonrpc': '2.0', 'result': 'Bar'} assert rv.status_code == 200 rv = client.post('/api', json={ 'id': 1, 'jsonrpc': '2.0', 'method': 'app.fn2', 'params': [':)'] }) assert rv.json == {'id': 1, 'jsonrpc': '2.0', 'result': 'Foo :)'} assert rv.status_code == 200
from json import dumps from flask import session from flask_jsonrpc import JSONRPC jsonrpc = JSONRPC(service_url='/api', enable_web_browsable_api=False) rooms = [{ 'users': [], 'cities': ['Астана', 'Архангельск', 'Коркино'], 'active': 0 }] users = [] @jsonrpc.method('game.getUsername') def check_username() -> str: username = session.get('username') if username: return username raise ValueError @jsonrpc.method('App.index') def index() -> str: return 'Hello world' @jsonrpc.method('App.print') def app_print(name: str) -> str: print(name)
from flask import Flask PROJECT_DIR, PROJECT_MODULE_NAME = os.path.split( os.path.dirname(os.path.realpath(__file__)) ) FLASK_JSONRPC_PROJECT_DIR = os.path.join(PROJECT_DIR, os.pardir) if os.path.exists(FLASK_JSONRPC_PROJECT_DIR) \ and not FLASK_JSONRPC_PROJECT_DIR in sys.path: sys.path.append(FLASK_JSONRPC_PROJECT_DIR) from flask_jsonrpc import JSONRPC app = Flask(__name__) jsonrpc = JSONRPC(app, '/api') def check_auth(username, password): return True @jsonrpc.method('App.index', authenticated=check_auth) def index(): return u'Welcome to Flask JSON-RPC' @jsonrpc.method('App.echo(name=str) -> str', validate=True, authenticated=check_auth) def echo(name='Flask JSON-RPC'): return u'Hello {0}'.format(name) if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)
db = SQLAlchemy() # redis链接对象 redis = FlaskRedis() # Session存储对象 session_store = Session() # 数据迁移实例对象 migrate = Migrate() # 日志对象 log = Log() # 初始化jsonrpc模块 jsonrpc = JSONRPC(service_url='/api') def init_app(config_path): """ 全局初始化 import_name Flask程序所在的包(模块),传 __name__ 就可以 其可以决定 Flask 在访问静态文件时查找的路径 static_path 静态文件访问路径(不推荐使用,使用 static_url_path 代替) static_url_path 静态文件访问路径,可以不传,默认为:/ + static_folder static_folder 静态文件存储的文件夹,可以不传,默认为 static template_folder 模板文件存储的文件夹,可以不传,默认为 templates """ # 创建app应用对象
import sys from flask import Flask PROJECT_DIR, PROJECT_MODULE_NAME = os.path.split( os.path.dirname(os.path.realpath(__file__))) FLASK_JSONRPC_PROJECT_DIR = os.path.join(PROJECT_DIR, os.pardir) if os.path.exists(FLASK_JSONRPC_PROJECT_DIR) \ and not FLASK_JSONRPC_PROJECT_DIR in sys.path: sys.path.append(FLASK_JSONRPC_PROJECT_DIR) from flask_jsonrpc import JSONRPC app = Flask(__name__) jsonrpc = JSONRPC(app, '/api', enable_web_browsable_api=True) @jsonrpc.method('App.index') def index(): return u'Welcome to Flask JSON-RPC' @jsonrpc.method('App.hello') def hello(name): return u'Hello {0}'.format(name) @jsonrpc.method('App.helloDefaultArgs') def hello_default_args(string='Flask JSON-RPC'): return u'We salute you {0}'.format(string)
from app import create_app, db from app.models import User from flask_script import Manager, Shell from flask_migrate import Migrate, MigrateCommand from flask_jsonrpc import JSONRPC import os # app = create_app(os.getenv('FLASK_CONFIG') or 'development') app = create_app('development') jsonrpc = JSONRPC(app, '/api', enable_web_browsable_api=True, auth_backend=User.authenticate) manager = Manager(app) migrate = Migrate(app, db) def make_shell_context(): return dict(app=app, db=db, User=User) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) # 载入jsonrpc的接口 import app.soapi.user import app.ansible2.api import app.soapi.asset import app.soapi.knowledge import app.soapi.project # 载入后台模板 if __name__ == '__main__': manager.run()