Building a user review with python flask [duplicate] - python

This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed last year.
I encountered some problems when trying to open the link provided by the flask. I have updated my code and when I run and open the link only hello world is displayed and not the current code. Can someone explain why pls?
Also the review page asks for the user to input their name and I tried this as code in the python flask although I can't check if this will get the user input due to the problem mentioned above. Does this code make sense?
from flask import Flask,request,render_template
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route("/")
def name():
name = request("name")

The problem is that you have the same route twice.
You have to use different routes for different endpoints.
Example:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route("/name")
def name():
return "This is the name endpoint."
When you go to /name, you should see 'This is the name endpoint.'.

Related

Template is not shown on the server

I am very new to Flask and Web development so sorry in advanced if I use incorrect terms.
I am trying to create a webpage using Python and Flask. To do so, I have the following:
from flask import Flask, request, render_template, redirect, url_for
from flask_assets import Environment, Bundle
app = Flask(__name__)
assets = Environment(app)
#app.route("/", methods=["GET", "POST"])
def login():
# Code to do the login
error = None
if request.method == 'POST':
# code checking the passwords. if correct:
return render_template('index.html')
# else:
# error
return render_template('login.html', error = error)
What this snippet of code does is to load the login.html where the user is asked to put an username and password and after checking if they are the ones expected, it loads index.html where the user can upload his or her data. Once the data is submitted a new function is called:
#app.route('/transform', methods=["POST"])
def transform():
f = request.files['data_file']
if not f:
return "No file"
# code
return render_template('message.html')
The problem is that while in local the message.html gets display once transform has finished, in the server it doesn't appear although the function eventually does what it's expected to do. The other two templates are correctly displayed both in local and in the server. Could it be due to be in a different route?
The index.html is defined with action='\transform', in case it may give a hint.
Any idea of why could this be happening?

Flask Error When I run program

I have friend helping with English this time.
I have more problems with getting new route to loading.
I have this testing code:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('main.html')
#app.route('/order')
def index():
return render_template('order.html')
if __name__ == '__main__':
app.run()
And I get this error:
View function mapping is overwriting an existing endpoint function: index
Please help me. I hope English better.
You define index() two times. You have to change name one of the function.
You are defining a function index twice in the same scope. The flask decorator is making it sound more complicated than that, is all.

Print JSON Data in output within FLASK [duplicate]

This question already has an answer here:
Print JSON Data - Flask [closed]
(1 answer)
Closed 6 years ago.
So I have this test app (learning flask). It takes a username and a message input and displays it on the third page. The last "return" below spits out that data. I need to include the JSON equivalent of the data below it. I think I need to put 'username' and 'message' into a variable and call json dumps to return it also? killing myself over here.
from flask import Flask, render_template, request,
redirect, url_for,abort, session
import json
from json import dumps
app = Flask(__name__)
app.config['SECRET_KEY'] = 'F34TF$($e34D';
#app.route('/')
def home():
return render_template('index.html')
#app.route('/signup', methods=['POST'])
def signup():
session['username'] = request.form['username']
session['message'] = request.form['message']
return redirect(url_for('message'))
#app.route('/message')
def message():
if not 'username' in session:
return abort(403)
return render_template('message.html',
username=session['username'],message=session['message']),
if __name__ == '__main__':
app.run()
This is what you need. The page also has example. You can do something like below. Normally you would want to respond with either a html or json depending on the accept header. It defines what data the client is expecting.
If accept is 'application/json' use jsonify. if accept is 'text/html', then render your template. That way your page will be normal when loaded from browser, however when using a restclient with accept headers set appropriately, you get json responses.
from flask import request
#app.route('/message')
def message():
if not 'username' in session:
return abort(403)
if request.headers['accept'] == 'text/html':
return render_template('message.html',
username=session['username'],message=session['message'])
elif request.headers['accept'] == 'application/json':
return jsonify(
username=session['username'], message=session['message'])

Flask Url with Prefix [duplicate]

This question already has answers here:
Add a prefix to all Flask routes
(15 answers)
Closed 7 years ago.
I have a Flask App, which will run later as a "subpart" of a server and I am unsure how to configure that.
As an example:
localhost/OtherServer/rest/myFlask/
OtherServer is an IIS Website which normally handles all my requests, but for certain requsts control is handed to Flask - e.g. all routes which are found unter myFlask/*.
This already works thanks to WFASTCGI and some config magic, but in Flask I have to supply to the full URL for each route:
#app.route('/OtherServer/rest/myFlask/status')
I would like to only specify the part including or after myFlask, particularly because the firt part of the url is configurable in a C#-app and getting the name at runtime is a major headache.
So:
#app.route('/myFlask/status')
You can use blueprint, use the url_prefix parameter.
I'll show you a simple example:
view.py
from flask import Blueprint
my_blueprint = Blueprint('my_blueprint', __name__, template_folder='templates',
url_prefix='/OtherServer/rest')
#my_blueprint.route('/myFlask/status')
def index():
return 'Hello, world.'
...other routes...
in your app.py, you can
from flask import Flask
from my_app.view import my_blueprint
app = Flask(__name__)
app.register_blueprint(my_blueprint)

Flask redirect url with anchor

I have some problem with redirecting with anchors from python code.
My code:
func():
...
redirect(url_for('my_view', param=param, _anchor='my_anchor'))
This redirect didn't redirect me to #my_anchor.
In template link like:
works good... May be problem in flask function "redirect".
How I can use redirect with anchors in Flask?
Flask version 0.10.x
if your goal is to be redirected to a page with an anchor preselected in the url I think the problem may be connected to the function you have passed in the 'url_for'. Below is my attempt to do what you described.
views.py
from flask import Flask
from flask import redirect, url_for
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
#app.route('/myredirect')
def my_redirect():
return redirect(url_for('hello_world',_anchor='my_anchor'))
if __name__ == '__main__':
app.run()
This does not need a template, as as soon as you hit /myredirect you are redirected to / with anchor #my_anchor
After you get your views started with $ python views.py and navigate to http://127.0.0.1:5000/myredirect you end up on http://127.0.0.1:5000/#my_anchor
A short and simple way of doing this is
return redirect(url_for('hello_world') + '#my_anchor')
instead of
return redirect(url_for('hello_world',_anchor='my_anchor'))
which works because url_for returns a string for the endpoint.

Categories