Flask 是最流行的 Python 网络框架之一。它相对容易学习,而它的扩展 Flask-RESTful 使您能够快速构建 REST API。
小例子:
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class MyApi(Resource):
def get(self, date):
return {'date': 'if present'}
api.add_resource(MyApi, '/')
if __name__ == '__main__':
app.run()
用curl测试:
curl http://localhost:5000/ -d "data=base_64_image_content" -X PUT
根据 cmets 中的讨论,以下是如何使用 GCP Functions 构建 OCR REST API:
import re
import json
from google.protobuf.json_format import MessageToJson
from google.cloud import vision
from flask import Response
def detect_text(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <http://flask.pocoo.org/docs/0.12/api/#flask.Flask.make_response>`.
"""
client = vision.ImageAnnotatorClient()
image = vision.types.Image(content=request.data)
response = client.text_detection(image=image)
serialized = MessageToJson(response)
annotations = json.loads(serialized)
full_text = annotations['textAnnotations'][0]['description']
annotations = json.dumps(annotations)
r = Response(response=annotations, status=200, mimetype="application/json")
return r
您可以使用以下代码发出请求:
def post_image(path, URL):
headers = {'content-type': 'image/jpeg'}
img = open(path, 'rb').read()
response = requests.post(URL, data=img, headers=headers)
return response