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

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.

Related

Reactjs - Flask - Access to XMLHttpRequest has been blocked by CORS policy:

I am new to web development. I deployed a web application whose front-end and react js and the back end is Flask python.
React and Flask are hosted on the same server (I use the o2switch server).
I followed all the tutorials to make the CORS problem bother me more, but it didn't solve the problem.
Here is a snippet of my current Flask code:
`
from calcul import Calcul, CoefficientCM
import pandas as pd
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
from flask_ngrok import run_with_ngrok
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "http://app.prot.sc1i.un.wf", "allow_headers": "*", "expose_headers": "*"}})
run_with_ngrok(app)
app.config['CORS_HEADERS'] = 'Content-Type'
def options(self):
pass
#app.route('/calcul', methods=['POST'], strict_slashes=False)
#cross_origin(origin='http://app.prot.sc1i.un.wf',headers=['Content-Type','Authorization'], supports_credentials=True)
def main():
response = request.get_json()
The detailed error on chrome is as follows:
Could you tell me how to solve this CORS problem please.

Proper way to serve React frontend with Flask-RestX?

I'm trying to make a website where the APIs are defined with Flask-RestX and the React frontend can use those APIs. However, with the code below, and after running FLASK_APP=app.py flask run --host=0.0.0.0 --port=8000, the server won't return the index.html. I just get 404s. If I remove the doc="/documentation", then the / page becomes the swagger documentation. What should I do here?
from flask import Flask, send_from_directory
from flask_restx import Resource, Api
from .src.endpoints.endpoints import Endpoints
app = Flask(__name__, static_folder="frontend/build")
api = Api(app,
title="app",
version="v0.1",
doc="/documentation")
api.add_resource(Endpoints, "/endpoints")
#app.route("/")
def index():
return send_from_directory(app.static_folder,'index.html')

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

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

Unable to access formdata from Axios POST to Flask

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.

Categories