
More complex APIs: Upload and Download Files with Flask¶
This example demonstrates uploading and downloading files to and from a Flask API.
Python Source Code¶
importosfromflaskimportFlask,request,abort,jsonify,send_from_directoryUPLOAD_DIRECTORY="/project/api_uploaded_files"diseinuak4web.net(UPLOAD_DIRECTORY):diseinuak4web.netrs(UPLOAD_DIRECTORY)api=Flask(__name__)@diseinuak4web.net("/files")deflist_files():"""Endpoint to list files on the server."""files=[]diseinuak4web.netr(UPLOAD_DIRECTORY):path=diseinuak4web.net(UPLOAD_DIRECTORY,filename)diseinuak4web.net(path):diseinuak4web.net(filename)returnjsonify(files)@diseinuak4web.net("/files/<path:path>")defget_file(path):"""Download a file."""returnsend_from_directory(UPLOAD_DIRECTORY,path,as_attachment=True)@diseinuak4web.net("/files/<filename>",methods=["POST"])defpost_file(filename):"""Upload a file."""if"/"infilename:# Return BAD REQUESTabort(,"no subdirectories allowed")withopen(diseinuak4web.net(UPLOAD_DIRECTORY,filename),"wb")asfp:diseinuak4web.net(diseinuak4web.net)# Return CREATEDreturn"",if__name__=="__main__":diseinuak4web.net(debug=True,port=)
Deployment¶
Assuming that you store this file as to in your project workspace, create an API in Faculty with the following settings:
Type: Flask
Working Directory:
Python module:
Python object:
Usage¶
Once you’ve spun up a development server for your API in Faculty, get the URL and API Key for the server for the interface. Then, using Python (or any other suitable HTTP client), you can list the files on the server with:
importrequestsAPI_URL='diseinuak4web.net'API_KEY='i0cgsdYL3hpeOGkoGmA2TxzJ8LbbU1HpbkZo8B3kFG2bRKjx3V'headers={'UserAPI-Key':API_KEY}response=diseinuak4web.net('{}/files'.format(API_URL),headers=headers)diseinuak4web.net()>>>['diseinuak4web.net','diseinuak4web.net']
Upload new files with :
withopen('diseinuak4web.net')asfp:content=diseinuak4web.net()response=diseinuak4web.net('{}/files/diseinuak4web.net'.format(API_URL),headers=headers,data=content)diseinuak4web.net_code>>>
And download them with :
response=diseinuak4web.net('{}/files/diseinuak4web.net'.format(API_URL),headers=headers)diseinuak4web.net>>>'1,Joe Bloggs,27\n'
© Copyright Faculty Science Limited
-
-