Last active
March 17, 2021 06:37
-
-
Save bswen/f48580b09727839e656f639475aeea3d to your computer and use it in GitHub Desktop.
demo how to upload file with flask_restful api, and demo how to read both the uploaded file and the http fields with flask. The blog url: https://bswen.com/2021/03/others-how-to-upload-file-using-flask-restful-api.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask | |
from flask_restful import reqparse, Api, Resource | |
import werkzeug | |
import os | |
app = Flask(__name__) | |
api = Api(app) | |
UPLOAD_DIR="/Users/bswen/work/python/myutils/learn_flask/uploaded_files" | |
Books = { | |
'book1': {'title': 'build an API'}, | |
'book2': {'title': 'test 1'}, | |
'book3': {'title': 'profit!'}, | |
} | |
# shows a list of all books, and lets you POST to add new titles | |
class BookList(Resource): | |
def __init__(self): | |
self.parser = reqparse.RequestParser() | |
def get(self): | |
return Books | |
def post(self): | |
self.parser.add_argument("bookfile", type=werkzeug.datastructures.FileStorage, location='files') | |
self.parser.add_argument('title') | |
args = self.parser.parse_args() | |
book_id = int(max(Books.keys()).lstrip('book')) + 1 | |
bookfile = args.get("bookfile") | |
book_id = 'book%i' % book_id | |
Books[book_id] = {'title': args['title']} | |
bookfile.save(os.path.join(UPLOAD_DIR, bookfile.filename)) | |
return Books, 201 | |
api.add_resource(BookList, '/books') | |
if __name__ == '__main__': | |
app.run(debug=True, port=8080, host="0.0.0.0") | |
# curl -v -X POST -H "Content-Type: multipart/form-data" -F "title=aabb" -F "cbbfile=@test.zip" http://localhost:8080/books |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment