my code:
from flask import Flask, render_template,request, redirect
#app.route("/wait", methods=['GET', 'POST'])
def wait():
print(5)
return render_template("wait")
#app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
data = request.form
print(data["theme"])
print(data["subreddit"])
return redirect("/wait")
else:
return render_template("index.html")
my error:
RuntimeError: Attempt to access app outside of a relevant context
You need to instantiate app in your code. Add this line under your import:
app = Flask(__name__)
Related
I am not sure if its a circular import issue but havent got an error indicating so. How do i make my app display the routes!!!!!
Here is my application structure
My init.py file is where i have created my FLask application instance. I have tried to import views into it but it refuses to work
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'e14c80be9484a60c179678f7a0c5d6f1'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
Here is my views.py file, i imported the app instance in it to get my routes working but in vain
from flask import render_template, url_for, flash, redirect
from crud_app import app
from crud_app.forms import RegistrationForm, LoginForm
#app.route('/')
#app.route('/index')
def index():
return render_template('index.html')
#app.route('/home')
def home():
return render_template('home.html', title='HomePage')
#app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
if form.email.data == 'andy#gmail.com' and form.password.data == 'password':
flash('Your LogIn was a Success')
return redirect(url_for('home'))
else:
flash('Login Unsuccessful, Please check your Email and Password ')
return render_template('login.html', title='loginPage', form=form)
#app.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
flash(f'Welcome { form.username.data} ,your account has been created!')
return redirect(url_for('home'))
return render_template('register.html', title='RegisterPage', form=form)
from flask import Flask, session, request, render_template
import model //model.py
app = Flask(_name__)
session.key = "randomkey"
#app.route("/", methods = ['POST', 'GET'])
def hello():
if request.method == 'POST':
//Some cide that takes input from index.html and stores in python variables
prediction = model.make_prediction(modelinput)
session["prediction"] = prediction
return render_template("index.html")
#app.route("/prediction", methods = ['POST', 'GET'])
def submit():
final_prediction = session.get("prediction", None)
return render_template("prediction.html", predic = final_prediction)
Now even though I use a session variable to pass the value between the sessions, I get a None value as the output. Why is that?
Try adding this line in your code:
from flask import Flask, session, request, render_template
import model //model.py
app = Flask(_name__)
app.config["SECRET_KEY"] = "topSecret"
i am getting error 404 while running this
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. how do i need to run the server ? please help
from flask import Flask
from flask import render_template
from flask import request
app = Flask(__name__, template_folder="templates/")
app.route("/login", method=['POST', 'GET'])
def index():
greeting = "Hello World"
if request.method == "POST":
name = request.form['name']
greet = request.form['greet']
greeting = f"{greet}, {name}"
return render_template("index.html", greeting=greeting)
else:`enter code here`
return render_template("hello_form.html")
if __name__ == "__main__":
app.run(debug=True)
You need to replace
app.route("/login", method=['POST', 'GET'])
By
#app.route("/login", methods=['POST', 'GET'])
Edit: also, methods
It's the most basic thing to ask but #app.route('/') is not working on my Linux server.
Below is the code :
from flask import Flask, jsonify, request
from app import models
import json
import time
app = Flask(__name__)
app.url_map.strict_slashes = True
#app.route('/')
def blank():
return 'Hello ABC!'
#app.route('/driftking')
def blank2():
return 'Hello driftking!'
# dynamic route
#app.route("/test/<search_query>")
def search(search_query):
return search_query
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return "POST METHOD"
elif request.method == 'GET':
return "GET REQUEST ARE NOT ALLOWED"
if __name__ == '__main__':
app.run(debug=True)
app.run()
Very basic app, all's working fine on local machine but not on my linux server.
E.g. if I load http://xxx.xxx.xxx.xxx/projectname ---- it shows Hello ABC!
If I load http://xxx.xxx.xxx.xxx/projectname/driftking -- it redirects me to http://xxx.xxx.xxx.xxx ( i.e my server's homepage)
If I load http://xxx.xxx.xxx.xxx/projectname/test/search -- 404 error not found
If I load http://xxx.xxx.xxx.xxx/projectname/login -- it redirects me to http://xxx.xxx.xxx.xxx ( i.e my server's homepage)
127.0.0.1 - - [24/Nov/2017 19:37:01] "POST //login HTTP/1.1" 405 -
^^This is what I get on terminal. I don't understand why I get two leading slashes everytime.
But If do http://xxx.xxx.xxx.xxx/projectname/insert-any-word/login , my post req get's executed. At the same time on local machine i dont get two leading slashes // to the path and thus the request get's processed.
There are a couple of things wrong but try this, you'll need a proxy to help with the rerouting.
from flask import Flask, jsonify, request
from app import models
import json
import time
from werkzeug.contrib.fixers import ProxyFix
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
app.url_map.strict_slashes = False
#app.route('/')
def blank():
return 'Hello ABC!'
#app.route('/driftking')
def blank2():
return 'Hello driftking!'
# dynamic route
#app.route("/test/<search_query>")
def search(search_query):
return search_query
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return "POST METHOD"
elif request.method == 'GET':
return "GET REQUEST ARE NOT ALLOWED"
if __name__ == '__main__':
app.run(debug=True)
Consider I have this following code:
from flask import Flask
from flask import request
app = Flask(__name__)
#app.route('/test', methods=['GET'])
def get():
if request.method == 'GET':
return 'hello'
#app.route('/post', methods=['POST'])
def post():
if request.method == 'POST':
name = request.form['name']
return name
if __name__ == '__main__':
app.run()
I run the code and the server starts with these two API endpoints.
Now, I want to register one more endpoint in the same flask app without restarting the currently server, so that any transactions going on the existing endpoints are not interrupted.
Is there a way I can register a new endpoint with closing/restarting the server on the same flask app?
You can register new rules at any point in your code using Flasks add_url_rule() function. This function is actually called by the route() decorator as well.
#app.route('/')
def index():
pass
Is equivalent to:
def index():
pass
app.add_url_rule('/', 'index', index)