Unable to access formdata from Axios POST to Flask - python

I have a flask api that I am starting and I am sending a post generated by AXIOS.post:
from flask import Flask, request
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = "A REEALLY REALLY LONG KEY"
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://ppsadmin:#localhost/ppsportal"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
#app.route("/login")
def login():
data = request.form
print(data)
return json.dumps({"success":True})
if __name__ == '__main__':
app.run()
When I run this code Flask returns a 405 error and I am unable to access the fields.

Resolved:
I forgot to wrap the app in CORS.

Related

Why flask app run but browser is not loading the page?

I was developing a web application and it was woking fine, then I closed the project and re-opened it after a few hours, the project ran without error, but when I go to localhost:5000 it doesn't even load. I tried the same project in another laptop and it works perfectly.
I also tried a simple project in the problematic one like this. The program run, but the browser won't load the page, also here if I use my second laptop it works perfectly. What I should do to fix? Literally like 2 hours ago was working fine
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world(): # put application's code here
return 'Hello World!'
if __name__ == '__main__':
app.run()
My application code is:
from flask import Flask, render_template
from flask_login import current_user, LoginManager
from DaisPCTO.db import get_user_by_id
from flask_bootstrap import Bootstrap
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = "qwnfdopqwebnpqepfm"
Bootstrap(app)
login_manager = LoginManager()
login_manager.login_view = "auth_blueprint.login"
login_manager.init_app(app)
#app.route("/")
def home():
print("hello")
return render_template("page.html", user=current_user, roleProf = True if current_user.is_authenticated and current_user.hasRole("Professor") else False)
#login_manager.user_loader
def load_user(UserID):
return get_user_by_id(UserID)
from DaisPCTO.auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
from DaisPCTO.courses import courses as courses_blueprint
app.register_blueprint(courses_blueprint, url_prefix="/courses")
return app
i'm not putting all the blueprint, this is only the init.py file
In you application you don't run your app you just create a function
if __name__ == '__main__':
app = create_app()
app.run()
If you add this to your code you should be abble to see it in http://localhost:5000

How to solve Import "flask_cors" could not be resolved from source

I'm doing a web based project using flutter and flask. when I tried to use API to communicate between flutter and flask(note : I'm new to dealing with API's).
I got XML Http Request error, I tried all the solutions available but still no use and later found that installing flask-CORS module in flask can help resolve the issue. while importing flask-CORS module I faced with the above error.
Flask-CORS path and error
Flutter API code
from flask import Flask,request,jsonify
from flask_cors import CORS,cross_origin
app = Flask(__name__)
CORS(app)
app.config['ENV'] = "development"
#app.route('/auth',methods=["POST"])
#cross_origin()
def login():
res=request.get_json()
em=res["email"]
pwd=res["password"]
print(em+"\t"+pwd)
return "success"
if __name__ == "__main__":
app.run(debug=True)
https://flask-cors.readthedocs.io/en/latest/
Allow access to all apis that starts with /api from all origins.
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
or if you are testing from local try
cors = CORS(app, resources={r"/api/*": {"origins": ["http://localhost:5000/*"]}})
from flask import Flask,request,jsonify
from flask_cors import CORS,cross_origin
app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
app.config['ENV'] = "development"
#app.route('/auth',methods=["POST"])
#cross_origin()
def login():
res=request.get_json()
em=res["email"]
pwd=res["password"]
print(em+"\t"+pwd)
return "success"
if __name__ == "__main__":
app.run(debug=True)

flask automatic redirects when I start the server

I have a bare-minimum getting started with flask code. When I run server my terminal gets flooaded with 405 URL call(I am not making API calls explicitly from anywhere) No idea why it's doing that.
views.py
from app import app
from flask import jsonify
#app.route('/')
def index():
return jsonify({'message': 'Hello, World!'})
app.py
from flask import Flask
from flask_restful import Api
app = Flask(__name__)
api = Api(app)
import views, models, resources
api.add_resource(resources.UserRegistration, '/registration')
api.add_resource(resources.UserLogin, '/login')
api.add_resource(resources.UserLogoutAccess, '/logout/access')
api.add_resource(resources.UserLogoutRefresh, '/logout/refresh')
api.add_resource(resources.TokenRefresh, '/token/refresh')
api.add_resource(resources.AllUsers, '/users')
api.add_resource(resources.SecretResource, '/secret')
SS of the error

Splitting Flask code into different files [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Below is the python flask code.
All I want to do is split the code into different files as in
all the routes in views.py, configure db in db.py and use them in app.py or where ever required.
Also I want to use db in some of the routes so how do I call it in views.py
from flask import Flask, render_template, request, redirect, make_response, jsonify
from flask_mysqldb import MySQL
from flask_cors import CORS, cross_origin
import yaml
app = Flask(__name__)
# middleware
cors = CORS(app)
# configure db
db = yaml.safe_load(open('db.yaml'))
app.config['MYSQL_HOST'] = db['mysql_host']
app.config['MYSQL_USER'] = db['mysql_user']
app.config['MYSQL_PASSWORD'] = db['mysql_password']
app.config['MYSQL_DB'] = db['mysql_db']
mysql = MySQL(app)
# routes
#app.route("/", methods=['POST'])
def index():
cur = mysql.connection.cursor()
sql_select_query_check = """UPDATE users SET Password = %s, Password_Status = %s WHERE ID = %s"""
cur.execute(sql_select_query_check, (hashcode, 1, userid[0]))
mysql.connection.commit()
return jsonify({"message": "password updated"})
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
In flask documentation you can see Larger Applications which shows how to split code. And it mentions that main problem can be circular import - main imports views which has to import main to get app. The same problem is with db.py which would need to import main to get app
I move app to separated file application.py to skip circular import
I don't run code and maybe it would need to import mysql to views.py
But maybe it should be done with Blueprint() or with functions which will be imported to main.py and run with argument app.
application.py
from flask import Flask
app = Flask(__name__)
db.py
from application import app
from flask_mysqldb import MySQL
import yaml
db = yaml.safe_load(open('db.yaml'))
app.config['MYSQL_HOST'] = db['mysql_host']
app.config['MYSQL_USER'] = db['mysql_user']
app.config['MYSQL_PASSWORD'] = db['mysql_password']
app.config['MYSQL_DB'] = db['mysql_db']
mysql = MySQL(app)
views.py
from application import app
#app.route("/", methods=['POST'])
def index():
cur = mysql.connection.cursor()
sql_select_query_check = """UPDATE users SET Password = %s, Password_Status = %s WHERE ID = %s"""
cur.execute(sql_select_query_check, (hashcode, 1, userid[0]))
mysql.connection.commit()
return jsonify({"message": "password updated"})
main.py
from application import app
from flask import render_template, request, redirect, make_response, jsonify
from flask_cors import CORS, cross_origin
from views import *
# middleware
cors = CORS(app)
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
EDIT:
Version with code in functions init() and without application.py - but I didn't test if it will works. But it starts looking like code with Blueprint
db.py
from flask_mysqldb import MySQL
import yaml
def init(app):
db = yaml.safe_load(open('db.yaml'))
app.config['MYSQL_HOST'] = db['mysql_host']
app.config['MYSQL_USER'] = db['mysql_user']
app.config['MYSQL_PASSWORD'] = db['mysql_password']
app.config['MYSQL_DB'] = db['mysql_db']
return MySQL(app)
views.py
def init(app, mysql):
#app.route("/", methods=['POST'])
def index():
cur = mysql.connection.cursor()
sql_select_query_check = """UPDATE users SET Password = %s, Password_Status = %s WHERE ID = %s"""
cur.execute(sql_select_query_check, (hashcode, 1, userid[0]))
mysql.connection.commit()
return jsonify({"message": "password updated"})
main.py
from flask import Flask
from flask import render_template, request, redirect, make_response, jsonify
from flask_cors import CORS, cross_origin
import db
import views
app = Flask(__name__)
# middleware
cors = CORS(app)
myslq = db.init(app)
views.init(app, mysql)
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
But I would rather keep views with app = Flask(__name__) in one file.

How to integrate Angular 6 Single Page Application with FLASK architecture?

I'm using one of the Angular 6 template for frontend and using Python to do some heavier computation of images.
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__,static_url_path='')
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
#app.route('/')
def index():
return app.send_static_file('./index.html')
#app.route('/api/test')
def test():
socketio.emit('resp', {'data': 'got it!'});
return "done"
if _name_ == '__main__':
socketio.run(app)
I tried integrating angular 6 template with FLASK it worked for me but on refresh of the application or by changing state it throws me following error
"Page not found 404"
Please, help with integrating the Single Page Application.

Categories