除了使用Swagger UI自动为我们的API生成交互式文档的能力之外,使用Flask-RESTplus而不是Flask-RESTful有什么真正的优势吗?
我已经开发了一个带有Flask Restful的小型只写REST api,它接受来自少数可能具有更改IP地址的客户端的PUT请求.我的客户是运行AngularJS前端的嵌入式Chromium客户端; 他们使用简单的魔法密钥对我的API进行身份验证 - 这对我的规模非常有限.
我正在测试现在部署我的API,我注意到Angular客户端正在尝试向我的Flask服务发送OPTIONS http方法.我的API同时回复了404(因为我还没有编写OPTIONS处理程序,只有PUT处理程序).似乎在发送非POST或GET的跨域请求时,Angular将在服务器上发送一个pre-flight OPTIONS方法,以确保在发送实际请求之前接受跨域请求.是对的吗?
无论如何,我如何允许所有跨域PUT请求到Flask Restful API?我之前使用了带有(非宁静的)Flask实例的cross-domaion装饰器,但是我是否需要在我的API中编写OPTIONS处理程序?
app.py
from flask import Flask, render_template, request,jsonify,json,g
import mysql.connector
app = Flask(__name__)
**class TestMySQL():**
@app.before_request
def before_request():
try:
g.db = mysql.connector.connect(user='root', password='root', database='mysql')
except mysql.connector.errors.Error as err:
resp = jsonify({'status': 500, 'error': "Error:{}".format(err)})
resp.status_code = 500
return resp
@app.route('/')
def input_info(self):
try:
cursor = g.db.cursor()
cursor.execute ('CREATE TABLE IF NOT EXISTS testmysql (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(40) NOT NULL, \
email VARCHAR(40) NOT NULL UNIQUE)')
cursor.close()
Run Code Online (Sandbox Code Playgroud)
test.py
from app import *
class Test(unittest.TestCase):
def test_connection1(self):
with …Run Code Online (Sandbox Code Playgroud) 我想以下列方式创建支持GET请求的资源:
/bar?key1=val1&key2=val2
Run Code Online (Sandbox Code Playgroud)
我尝试了这段代码,但它没有用
app = Flask(__name__)
api = Api(app)
class BarAPI(Resource):
def get(key1, key2):
return jsonify(dict(data=[key1, key2]))
api.add_resource(BarAPI, '/bar', endpoint='bar')
Run Code Online (Sandbox Code Playgroud)
谢谢!
在我的Flask-RESTful API中,假设我有两个对象,用户和城市.这是1对多的关系.现在,当我创建API并向其添加资源时,我似乎只能将非常简单的常规URL映射到它们.这是代码(没有包含无用的东西):
class UserAPI(Resource): # The API class that handles a single user
def __init__(self):
# Initialize
def get(self, id):
# GET requests
def put(self, id):
# PUT requests
def delete(self, id):
# DELETE requests
class UserListAPI(Resource): # The API class that handles the whole group of Users
def __init__(self):
def get(self):
def post(self):
api.add_resource(UserAPI, '/api/user/<int:id>', endpoint='user')
api.add_resource(UserListAPI, '/api/users/', endpoint='users')
class CityAPI(Resource):
def __init__(self):
def get(self, id):
def put(self, id):
def delete(self, id):
class CityListAPI(Resource):
def __init__(self):
def get(self):
def …Run Code Online (Sandbox Code Playgroud) 使用burn-restful微框架,我在构建一个RequestParser验证嵌套资源的问题时遇到了麻烦.假设表单的预期JSON资源格式:
{
'a_list': [
{
'obj1': 1,
'obj2': 2,
'obj3': 3
},
{
'obj1': 1,
'obj2': 2,
'obj3': 3
}
]
}
Run Code Online (Sandbox Code Playgroud)
每个项目a_list对应一个对象:
class MyObject(object):
def __init__(self, obj1, obj2, obj3)
self.obj1 = obj1
self.obj2 = obj2
self.obj3 = obj3
Run Code Online (Sandbox Code Playgroud)
...然后,可以使用以下形式创建RequestParser:
from flask.ext.restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('a_list', type=MyObject, action='append')
Run Code Online (Sandbox Code Playgroud)
...但是你如何验证MyObject里面每个字典的嵌套a_list?或者,这是错误的方法吗?
对应的API对应于将每个处理MyObject为对象文字,并且可能有一个或多个传递给服务; 因此,扁平化资源格式不适用于这种情况.
我是Flask(&Flask-Restful)的新手.
我的问题:a的json参数POST设置为NONE(不工作).
我可以form-data使用POSTMANchrome的插件来获取参数.但是,当我切换到raw(&feed a json)时,它无法读取json并为NONE我的所有参数分配一个.
我已经阅读了一些与此相关的stackoverflow帖子:link1,link2,link3 ......这些都没有帮助我.
我使用python-2.6,Flask-Restful-0.3.3,Flask-0.10.1,Chrome,POSTMAN在Oracle的Linux 6.5.
Python代码 app.py:
from flask import Flask, jsonify
from flask_restful import reqparse, abort, Api, Resource
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('username', type=str)
parser.add_argument('password', type=str)
class HelloWorld(Resource):
def post(self):
args = parser.parse_args()
un = str(args['username'])
pw = str(args['password']) …Run Code Online (Sandbox Code Playgroud) 我使用flask-restful来创建我的API.我用于flask-jwt启用基于身份验证JWT.现在我需要做授权.
我试过把我的授权装饰器.
test.py(/ test api)
from flask_restful import Resource
from flask_jwt import jwt_required
from authorization_helper import authorized_api_user_type
class Test(Resource):
decorators = [jwt_required(), authorized_api_user_type()]
def get(self):
return 'GET OK'
def post(self):
return 'POST OK'
Run Code Online (Sandbox Code Playgroud)
基本上为了处理基本授权,我需要访问current_identity并检查它的类型.然后基于它的类型我将决定用户是否有权访问api/resources.
但current_identity似乎是empty那个装饰者.因此,要间接获取它,我必须看到代码jwt_handler并在那里完成工作.
authorization_helper.py
from functools import wraps
from flask_jwt import _jwt, JWTError
import jwt
from models import Teacher, Student
def authorized_api_user_type(realm=None, user_type='teacher'):
def wrapper(fn):
@wraps(fn)
def decorator(*args, **kwargs):
token = _jwt.request_callback()
if token is None: …Run Code Online (Sandbox Code Playgroud) 使用方法很容易使用flask-restful传播错误消息到客户端abort(),例如
abort(500, message="Fatal error: Pizza the Hutt was found dead earlier today
in the back seat of his stretched limo. Evidently, the notorious gangster
became locked in his car and ate himself to death.")
Run Code Online (Sandbox Code Playgroud)
这将生成以下json输出
{
"message": "Fatal error: Pizza the Hutt was found dead earlier today
in the back seat of his stretched limo. Evidently, the notorious gangster
became locked in his car and ate himself to death.",
"status": 500
}
Run Code Online (Sandbox Code Playgroud)
有没有办法用其他成员自定义json输出?例如:
{
"sub_code": 42,
"action": "redirect:#/Outer/Space" …Run Code Online (Sandbox Code Playgroud) [根据/sf/answers/3245896181/,标题应参考集成测试而不是单元测试]
假设我想测试以下Flask API(从这里开始):
import flask
import flask_restful
app = flask.Flask(__name__)
api = flask_restful.Api(app)
class HelloWorld(flask_restful.Resource):
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
if __name__ == "__main__":
app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)
将此保存flaskapi.py并运行后,在同一目录中运行脚本test_flaskapi.py:
import unittest
import flaskapi
import requests
class TestFlaskApiUsingRequests(unittest.TestCase):
def test_hello_world(self):
response = requests.get('http://localhost:5000')
self.assertEqual(response.json(), {'hello': 'world'})
class TestFlaskApi(unittest.TestCase):
def setUp(self):
self.app = flaskapi.app.test_client()
def test_hello_world(self):
response = self.app.get('/')
if __name__ == "__main__":
unittest.main()
Run Code Online (Sandbox Code Playgroud)
两个测试都通过了,但对于第二个测试(在TestFlaskApi类中定义),我还没有弄清楚如何断言JSON响应是否符合预期(即{'hello': 'world'}).这是因为它是一个实例flask.wrappers.Response(可能基本上是一个Werkzeug响应对象(参见http://werkzeug.pocoo.org/docs/0.11/wrappers/)),但我找不到相应的Response …