- Instead of writing custom methods for http response and routing
engines you can use flask a lighwieght framwork that provide routing
engine and all features and security to the app and this also provide
necessary things to manage all kind of http requests
Solution 1 :
Solution 2 :
Please maintain below structure in your root directory
app.py
from flask import Flask
app = Flask(__name__)
main.py
from flask_cors import CORS
import os
from app import app
# allowing cross browser request with cors configuration
CORS(app, supports_credentials=True,methods=['GET', 'HEAD', 'POST', 'OPTIONS', 'PUT', 'PATCH', 'DELETE'])
if __name__ == "__main__":
app.session_type = os.getenv('SESSION_TYPE')
app.run(debug=os.getenv('DEBUG'), host=os.getenv(
'SERVER_HOST'), port=os.getenv('SERVER_PORT'))
then execute the python main.py it will activate all routes enjoyy!!
Problem :
I have a HTTP Server in Python which is able to take and save files sent via POST request. However, now I am trying to download requested files with GET request. Basically, I want to send a GET request with a filename and I want my server to offer me a file to download. How would I do so?
My code so far:
class S(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def _html(self, message):
"""This just generates an HTML document that includes `message`
in the body. Override, or re-write this do do more interesting stuff.
"""
content = f"<html><body><h1>{message}</h1></body></html>"
return content.encode("utf8") # NOTE: must return a bytes object!
def do_GET(self):
self._set_headers()
self.wfile.write(self._html("hi!"))
def do_HEAD(self):
self._set_headers()
def do_POST(self):
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
filename = form['file'].filename
data = form['file'].file.read()
open(filename, "wb").write(data)
self._set_headers()
self.wfile.write(self._html("hi!"))
Comments
Comment posted by Charnel
And so you’re having problem with sending GET request or server response?
Comment posted by RIYAJ MULLA
sure. what is the issue
Comment posted by privnote.com/bACFXtsH#fAE7d4XKj
I used privnotes as pastecode wasn’t working for me somehow.
Comment posted by RIYAJ MULLA
Its because you havent configured flask for cross server request use below code to configure it first install CORS pip install Flask-Cors==3.0.8 paste below codes in your main.py or where your app get bootstrapped CORS(app, supports_credentials=True,methods=[‘GET’, ‘HEAD’, ‘POST’, ‘OPTIONS’, ‘PUT’, ‘PATCH’, ‘DELETE’])
Comment posted by RIYAJ MULLA
what is the error? please install all dependencies that requires to run flask in your environment
Comment posted by privnote.com/wzFUYbBQ#Bl230GeJk
Oh, I think I understand now. This is my code. app: