👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!
For the following ajax
post request for Flask
(how can I use data posted from ajax in flask?):
$.ajax({
url: "http://127.0.0.1:5000/foo",
type: "POST",
contentType: "application/json",
data: JSON.stringify({"inputVar": 1}),
success: function( data ) {
alert( "success" + data );
}
});
I get a Cross Origin Resource Sharing (CORS)
error:
No "Access-Control-Allow-Origin" header is present on the requested resource.
Origin "null" is therefore not allowed access.
The response had HTTP status code 500.
I tried solving it in the two following ways, but none seems to work.
- Using Flask-CORS
This is a Flask
extension for handling CORS
that should make cross-origin AJAX possible.
- http://flask-cors.readthedocs.org/en/latest/
- How to enable CORS in flask and heroku
- Flask-cors wrapper not working when jwt auth wrapper is applied.
- Javascript - No 'Access-Control-Allow-Origin' header is present on the requested resource
My pythonServer.py using this solution:
from flask import Flask
from flask.ext.cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app, resources={r"/foo": {"origins": "*"}})
app.config["CORS_HEADERS"] = "Content-Type"
@app.route("/foo", methods=["POST","OPTIONS"])
@cross_origin(origin="*",headers=["Content-Type","Authorization"])
def foo():
return request.json["inputVar"]
if __name__ == "__main__":
app.run()
- Using specific Flask Decorator
This is an official Flask code snippet defining a decorator that should allow CORS
on the functions it decorates.
- http://flask.pocoo.org/snippets/56/
- Python Flask cross site HTTP POST - doesn't work for specific allowed origins
- http://chopapp.com/#351l7gc3
My pythonServer.py using this solution:
from flask import Flask, make_response, request, current_app
from datetime import timedelta
from functools import update_wrapper
app = Flask(__name__)
def crossdomain(origin=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
automatic_options=True):
if methods is not None:
methods = ", ".join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ", ".join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ", ".join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers["allow"]
def decorator(f):
def wrapped_function(*args, **kwargs):
if automatic_options and request.method == "OPTIONS":
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != "OPTIONS":
return resp
h = resp.headers
h["Access-Control-Allow-Origin"] = origin
h["Access-Control-Allow-Methods"] = get_methods()
h["Access-Control-Max-Age"] = str(max_age)
if headers is not None:
h["Access-Control-Allow-Headers"] = headers
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
@app.route("/foo", methods=["GET","POST","OPTIONS"])
@crossdomain(origin="*")
def foo():
return request.json["inputVar"]
if __name__ == "__main__":
app.run()
Can you please give some some indication of why that is?
👻 Read also: what is the best laptop for engineering students?
Solve Cross Origin Resource Sharing with Flask __del__: Questions
How can I make a time delay in Python?
5 answers
I would like to know how to put a time delay in a Python script.
Answer #1
import time
time.sleep(5) # Delays for 5 seconds. You can also use a float value.
Here is another example where something is run approximately once a minute:
import time
while True:
print("This prints once a minute.")
time.sleep(60) # Delay for 1 minute (60 seconds).
Answer #2
You can use the sleep()
function in the time
module. It can take a float argument for sub-second resolution.
from time import sleep
sleep(0.1) # Time in seconds
Solve Cross Origin Resource Sharing with Flask __del__: Questions
How to delete a file or folder in Python?
5 answers
How do I delete a file or folder in Python?
Answer #1
os.remove()
removes a file.os.rmdir()
removes an empty directory.shutil.rmtree()
deletes a directory and all its contents.
Path
objects from the Python 3.4+ pathlib
module also expose these instance methods:
pathlib.Path.unlink()
removes a file or symbolic link.pathlib.Path.rmdir()
removes an empty directory.
We hope this article has helped you to resolve the problem. Apart from Solve Cross Origin Resource Sharing with Flask, check other __del__-related topics.
Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.
By the way, this material is also available in other languages:
- Italiano Solve Cross Origin Resource Sharing with Flask
- Deutsch Solve Cross Origin Resource Sharing with Flask
- Français Solve Cross Origin Resource Sharing with Flask
- Español Solve Cross Origin Resource Sharing with Flask
- Türk Solve Cross Origin Resource Sharing with Flask
- Русский Solve Cross Origin Resource Sharing with Flask
- Português Solve Cross Origin Resource Sharing with Flask
- Polski Solve Cross Origin Resource Sharing with Flask
- Nederlandse Solve Cross Origin Resource Sharing with Flask
- 中文 Solve Cross Origin Resource Sharing with Flask
- 한국어 Solve Cross Origin Resource Sharing with Flask
- 日本語 Solve Cross Origin Resource Sharing with Flask
- हिन्दी Solve Cross Origin Resource Sharing with Flask
California | 2023-03-26
Simply put and clear. Thank you for sharing. Solve Cross Origin Resource Sharing with Flask and other issues with functools Python module was always my weak point 😁. I am just not quite sure it is the best method
Milan | 2023-03-26
Maybe there are another answers? What Solve Cross Origin Resource Sharing with Flask exactly means?. I just hope that will not emerge anymore
California | 2023-03-26
datetime Python module is always a bit confusing 😭 Solve Cross Origin Resource Sharing with Flask is not the only problem I encountered. Checked yesterday, it works!