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')
Related
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.
Hello everyone I'm trying to do something very simple but all the documentation out do this on the same file.
I want to use oauth in my flask app and this is my main.py file
from flask import Flask
from login_routes import login
from authlib.integrations.flask_client import OAuth
app = Flask(__name__)
oauth = OAuth(app)
app.register_blueprint(login)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
And my login_routes.py has these lines
from flask import Blueprint, render_template, url_for, redirect, session
from authlib.integrations.flask_client import OAuth
import settings
# OAuth config
google = oauth.register(
name='google',
client_id=settings.GOOGLE_CLIENT_ID,
client_secret=settings.GOOGLE_CLIENT_SECRET,
access_token_url=settings.GOOGLE_TOKEN_URI,
access_token_params=None,
authorize_url=settings.GOOGLE_AUTH_URI,
authorize_params=None,
api_base_url='https://www.googleapis.com/oauth2/v1/',
client_kwargs={'scope': 'openid profile email'}
)
However oauth is not declared in my login_routes.py, I dont know how to bring that variable from main instance to this other file, I tried importing main.py which on my brain makes no sense because that ends up on a circular reference error please let me know how to instantiate this correctly.
Try
In main.py
app = Flask(__name__)
oauth = OAuth(app)
# assign your oauth to a variable (property) of app instance
app.OAUTH = oauth
In login_routes.py
# This pulls in the app object
from flask import Blueprint, current_app as app
# Since you're registering 'login' as a blueprint in main.py, define it here
login = Blueprint('login', __name__)
# you can do access the oauth instance as app.OAUTH e.g
abc = app.OAUTH....
I tried to set up multiple Dash Apps inside a Flask App and use Flask Babel.
from flask import Flask, request
from flask_babel import Babel, gettext
from werkzeug.middleware.dispatcher import DispatcherMiddleware
def init_app():
"""Construct core Flask application."""
app = Flask(__name__, instance_relative_config=False)
app.config.from_object("config.Config")
babel = Babel(app)
#babel.localeselector
def get_locale():
return request.accept_languages.best_match(app.config["LANGUAGES"])
with app.app_context():
# Import parts of our core Flask app
from . import routes
from .plotly.sec import init_dashboard_sec
from .plotly.bafin import init_dashboard_bafin
# app = init_dashboard(app)
app = DispatcherMiddleware(app, {
"/s": init_dashboard_sec(app),
"/b": init_dashboard_bafin(app)
})
return app
However, since I added the babel decorated function I get the following error:
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
I tried to move the function to a different position but the error stayed the same.
I don't know if it is the correct solution but the following is working:
from flask import Flask, request
from flask_babel import Babel, gettext
from werkzeug.middleware.dispatcher import DispatcherMiddleware
def init_app():
"""Construct core Flask application."""
app = Flask(__name__, instance_relative_config=False)
app.config.from_object("config.Config")
babel = Babel(app)
with app.app_context():
# Import parts of our core Flask app
from . import routes
from .plotly.sec import init_dashboard_sec
from .plotly.bafin import init_dashboard_bafin
# app = init_dashboard(app)
app = DispatcherMiddleware(app, {
"/s": init_dashboard_sec(app),
"/b": init_dashboard_bafin(app)
})
#babel.localeselector
def get_locale():
return request.accept_languages.best_match(["de", "en"])
return app
So babel gets initialized outside of the app context but the localselector is inside the context. For me it does not make much sense since the localeselector is still out of a request context but its working.
if you are probably working on the the terminal testing stuff out and you get the error just do this
from your_app import create_app
app = create_app()
with app.test_request_context(
'/make_report/2017', data={'format': 'short'}):
##do something here
for more information you can vist this part of the docs to learn more https://flask.palletsprojects.com/en/2.1.x/reqcontext/
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
what are the exact steps i need to execute in order to enable error logging to browser so i don't check the error_log via console any more?
I'am using Flask under Apache + mod_wsgi.
If i place app.debug = True within my app it does not do anything.
from flask import Flask, request, redirect, render_template, url_for
application = Flask(__name__)
app = application
app.config['TESTING'] = True