python+flask实现API的方法
作者:kd丹妮儿 时间:2023-12-18 17:25:03
本文为大家分享了python+flask实现API的具体方法,供大家参考,具体内容如下
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/,即可看到一个网页:
Flask + flask_restful创建一个简单的应用程序:
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创建API: 获取post请求传递的json数据
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服务
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服务,启动服务后,无法停止服务,因为app内部循环没有结束!
来源:https://blog.csdn.net/kanghui_898/article/details/84025523
标签:python,flask,API
0
投稿
猜你喜欢
Vue对象的深层劫持详细讲解
2024-04-26 17:40:20
Python中dumps与dump及loads与load的区别
2021-10-01 09:13:20
javascript canvas实现雨滴效果
2024-04-17 10:02:45
Python+Tkinter制作猜灯谜小游戏
2021-09-24 19:43:17
js读写COOKIE实现记住帐号或密码的代码(js读写COOKIE)
2024-04-18 10:11:12
Python文件操作函数用法实例详解
2021-03-12 07:10:29
十分钟教会你用Python处理CSV文件
2022-02-05 02:24:12
解决Python import .pyd 可能遇到路径的问题
2023-06-30 14:33:33
SQL Server中如何快速获取表的记录总数
2008-12-05 15:59:00
python把数组中的数字每行打印3个并保存在文档中的方法
2022-08-13 19:15:30
mysql存储过程学习总结
2011-07-04 12:03:53
Thinkphp6.0中间件的具体使用
2024-04-30 08:47:21
Redis数据库基础与ASP.NET Core缓存实现
2024-01-26 18:19:09
tornado捕获和处理404错误的方法
2023-11-27 11:03:36
Python图像处理之膨胀与腐蚀的操作
2022-10-07 19:47:06
让长字符自动换行 比如URL和Email地址等
2008-07-01 14:41:00
Python Flask入门之模板
2023-10-05 01:44:10
使用numpy实现矩阵的翻转(flip)与旋转
2023-01-31 01:03:18
LRUCache的实现原理及利用python实现的方法
2022-06-26 06:51:51
Python使用sftp实现传文件夹和文件
2021-09-30 12:27:37