使用Python & Flask 实现RESTful Web API的实例
环境安装:
sudopipinstallflask
Flask是一个Python的微服务的框架,基于Werkzeug,一个WSGI类库。
Flask优点:
WritteninPython(thatcanbeanadvantage);
Simpletouse;
Flexible;
Multiplegooddeploymentoptions;
RESTfulrequestdispatching
RESOURCES
一个响应/articles和/articles/:id的API服务:
fromflaskimportFlask,url_for app=Flask(__name__) @app.route('/') defapi_root(): return'Welcome' @app.route('/articles') defapi_articles(): return'Listof'+url_for('api_articles') @app.route('/articles/') defapi_article(articleid): return'Youarereading'+articleid if__name__=='__main__': app.run()
请求:
curlhttp://127.0.0.1:5000/
响应:
GET/
Welcome
GET/articles
Listof/articles
GET/articles/123
Youarereading123
REQUESTS
GETParameters
fromflaskimportrequest @app.route('/hello') defapi_hello(): if'name'inrequest.args: return'Hello'+request.args['name'] else: return'HelloJohnDoe'
请求:
GET/hello
HelloJohnDoe
GET/hello?name=Luis
HelloLuis
RequestMethods(HTTPVerbs)
@app.route('/echo',methods=['GET','POST','PATCH','PUT','DELETE']) defapi_echo(): ifrequest.method=='GET': return"ECHO:GET\n" elifrequest.method=='POST': return"ECHO:POST\n" elifrequest.method=='PATCH': return"ECHO:PACTH\n" elifrequest.method=='PUT': return"ECHO:PUT\n" elifrequest.method=='DELETE': return"ECHO:DELETE"
请求指定requesttype:
curl-XPATCHhttp://127.0.0.1:5000/echo
GET/echo
ECHO:GET
POST/ECHO
ECHO:POST
RequestData&Headers
fromflaskimportjson @app.route('/messages',methods=['POST']) defapi_message(): ifrequest.headers['Content-Type']=='text/plain': return"TextMessage:"+request.data elifrequest.headers['Content-Type']=='application/json': return"JSONMessage:"+json.dumps(request.json) elifrequest.headers['Content-Type']=='application/octet-stream': f=open('./binary','wb') f.write(request.data) f.close() return"Binarymessagewritten!" else: return"415UnsupportedMediaType;)"
请求指定contenttype:
curl-H"Content-type:application/json"\
-XPOSThttp://127.0.0.1:5000/messages-d'{"message":"HelloData"}'
curl-H"Content-type:application/octet-stream"\
-XPOSThttp://127.0.0.1:5000/messages--data-binary@message.bin
RESPONSES
fromflaskimportResponse @app.route('/hello',methods=['GET']) defapi_hello(): data={ 'hello':'world', 'number':3 } js=json.dumps(data) resp=Response(js,status=200,mimetype='application/json') resp.headers['Link']='http://luisrei.com' returnresp
查看responseHTTPheaders:
curl-ihttp://127.0.0.1:5000/hello
优化代码:
fromflaskimportjsonify
使用
resp=jsonify(data) resp.status_code=200
替换
resp=Response(js,status=200,mimetype='application/json')
StatusCodes&Errors
@app.errorhandler(404) defnot_found(error=None): message={ 'status':404, 'message':'NotFound:'+request.url, } resp=jsonify(message) resp.status_code=404 returnresp @app.route('/users/',methods=['GET']) defapi_users(userid): users={'1':'john','2':'steve','3':'bill'} ifuseridinusers: returnjsonify({userid:users[userid]}) else: returnnot_found()
请求:
GET/users/2
HTTP/1.0200OK
{
"2":"steve"
}
GET/users/4
HTTP/1.0404NOTFOUND
{
"status":404,
"message":"NotFound:http://127.0.0.1:5000/users/4"
}
AUTHORIZATION
fromfunctoolsimportwraps defcheck_auth(username,password): returnusername=='admin'andpassword=='secret' defauthenticate(): message={'message':"Authenticate."} resp=jsonify(message) resp.status_code=401 resp.headers['WWW-Authenticate']='Basicrealm="Example"' returnresp defrequires_auth(f): @wraps(f) defdecorated(*args,**kwargs): auth=request.authorization ifnotauth: returnauthenticate() elifnotcheck_auth(auth.username,auth.password): returnauthenticate() returnf(*args,**kwargs) returndecorated
replacingthecheck_authfunctionandusingtherequires_authdecorator:
@app.route('/secrets')
@requires_auth
defapi_hello():
return"Shhhthisistopsecretspystuff!"
HTTPbasicauthentication:
curl-v-u"admin:secret"http://127.0.0.1:5000/secrets
SIMPLEDEBUG&LOGGING
Debug:
app.run(debug=True)
Logging:
importlogging file_handler=logging.FileHandler('app.log') app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) @app.route('/hello',methods=['GET']) defapi_hello(): app.logger.info('informing') app.logger.warning('warning') app.logger.error('screamingbloodymurder!') return"checkyourlogs\n"
以上这篇使用Python&Flask实现RESTfulWebAPI的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。