欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python+flask实现API的方法

程序员文章站 2022-07-17 16:30:22
本文为大家分享了python+flask实现api的具体方法,供大家参考,具体内容如下 flask 框架 #-*-coding:utf-8-*-...

本文为大家分享了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/,即可看到一个网页:

python+flask实现API的方法

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内部循环没有结束!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。