python+flask實現(xiàn)API的方法
本文為大家分享了python+flask實現(xiàn)API的具體方法,供大家參考,具體內(nèi)容如下
Flask 框架
#-*-coding:utf-8-*-
#pip install flask
#pip install flask-restful
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "hello world!"
if __name__ == '__main__':
app.run(debug=True)
pycharm運行該程序后,在瀏覽器輸入http://127.0.0.1:5000/,即可看到一個網(wǎng)頁:

Flask + flask_restful創(chuàng)建一個簡單的應(yīng)用程序:
from flask import Flask
from flask_restful import Resource,Api
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def get(self):
return {"hello":"world"}
api.add_resource(HelloWorld,'/')
if __name__ == '__main__':
app.run(debug=True)
python+flask創(chuàng)建API: 獲取post請求傳遞的json數(shù)據(jù)
from flask import Flask,abort,jsonify,make_response,request
app = Flask(__name__)
@app.route('/analyze/' ,methods=['POST'])
def call_wiscan_analyze():
if not request.json or not 'path' in request.json:
abort(400)
path = request.json['path']
if __name__ == '__main__':
app.run(port='50055',debug=True)
請求:
from requests import post
if __name__ == '__main__':
path='"F:/nb_org_data/86574FG01/2013/1029/0008/86574FG01201310290008.img"'
ret = post('http://localhost:50055/analyze/',json={'path':path})
print(ret.text)
將API封裝為win32服務(wù)
import win32serviceutil
import win32service
import win32event
import win32timezone
from flask import Flask,abort,jsonify,make_response,request
import threading
app = Flask(__name__)
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
@app.route('/analyze/' ,methods=['POST'])
def call_wiscan_analyze():
if not request.json or not 'path' in request.json:
abort(400)
path = request.json['path']
def thread_target():
app.run(port='50055', debug=True)
class GRPCWin32Client(win32serviceutil.ServiceFramework):
_svc_name_ = 'GRPCWin32Client'
_svc_display_name_ = 'Nuctech GRPC Client'
_svc_description_ = 'wiscan grpc client'
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
#self.logger = self._getLogger()
self.run = True
def SvcDoRun(self):
th = threading.Thread(target=thread_target)
th.start()
try:
while self.run:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
pass
pass
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
self.run = False
if __name__ == '__main__':
import sys
import servicemanager
if len(sys.argv) == 1:
try:
evtsrc_dll = os.path.abspath(servicemanager.__file__)
servicemanager.PrepareToHostSingle(GRPCWin32Client)
servicemanager.Initialize('GRPCWin32Client', evtsrc_dll)
servicemanager.StartServiceCtrlDispatcher()
except win32service.error as details:
import winerror
if details == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
win32serviceutil.usage()
else:
win32serviceutil.HandleCommandLine(GRPCWin32Client)
注意:
啟動一個線程運行app.run(),否則安裝完win32服務(wù),啟動服務(wù)后,無法停止服務(wù),因為app內(nèi)部循環(huán)沒有結(jié)束!
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Pytorch搭建簡單的卷積神經(jīng)網(wǎng)絡(luò)(CNN)實現(xiàn)MNIST數(shù)據(jù)集分類任務(wù)
這篇文章主要介紹了Pytorch搭建簡單的卷積神經(jīng)網(wǎng)絡(luò)(CNN)實現(xiàn)MNIST數(shù)據(jù)集分類任務(wù),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03
如何使Python中的print()語句運行結(jié)果不換行
這篇文章主要介紹了如何使Python中的print()顯示當前語句后不換行,print() 是一個常用函數(shù),但是每次,print()語句顯示后都會換行,本問我們就來節(jié)日如何使print()顯示當前語句后不換行,需要的朋友可以參考一下2022-03-03
python3.6環(huán)境安裝+pip環(huán)境配置教程圖文詳解
這篇文章主要介紹了python3.6環(huán)境安裝+pip環(huán)境配置教程圖文詳解,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-06-06

