Flask Error When I run program - python

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.

Related

Building a user review with python flask [duplicate]

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.'.

flask before_request can't access request variable

I have a simple flask app:
def create_app():
config_name = 'testing_local'
app = Flask(__name__)
app.config.from_object(CONFIG_BY_NAME[config_name])
app.url_map.converters['bool'] = BooleanConverter
#app.before_request
def incoming_request_logging():
print(request)
return app
I get the error:
Undefined variable 'request'
I thought the wrapper included the request object when called?
In this example, first approved answer seems like the request object is inherited?
Can anyone link me to a full example? How can I retrieve this variable?
I guess declaring this at top of your program might solve your issue, if I think what you said it is:
from flask import request

Access the 'g' global proxy when creating an app using a factory in Flask

When in debug mode I want to add a handle to a memcached server in g. A nice place to do that is in the factory create method (create_app in the tutorial).
However, access to g results in a RuntimeError: Working outside of application context. I could register a method using Flask.before_request, but I do not want to have a check for DEBUG mode running every time a user connects.
From what I've read, each request seems to get its own context instance, and with it its own g. Is there another way to retain per-app data for use in this way?
from flask import Flask
from flask import current_app
def create_app():
app = Flask(__name__)
# set your function
setattr(app, 'my_func', 'function')
return app
app = create_app()
#app.route('/')
def index():
return getattr(current_app, 'my_func')
if __name__ == '__main__':
app.run()

Catch-All URL example in flask-restful also catching /

There is a catch-all URL example for Flask:
from flask import Flask
app = Flask(__name__)
#app.route('/', defaults={'path': ''})
#app.route('/<path:path>')
def catch_all(path):
return 'You want path: %s' % path
if __name__ == '__main__':
app.run()
Decorators can be translated to the following to code look more similar to Flask-RESTful achieving the same functionality:
app.add_url_rule('/', 'catch_all', catch_all, defaults={'path': ''})
app.add_url_rule('/<path:path>', 'catch_all', catch_all, defaults={'path': ''})
If I'm right, this can be further translated to an equivalent Flask-RESTful app (at least debuging shows it creates the same URL routes):
class RESTapp(Resource):
def get(self, path):
# do get something
api.add_resource(RESTapp, '/', '/<path:path>', defaults={'path': ''})
The problem is that this app redirects all URLs to / and I can not get the requested path in get() function. I want to handle all paths ( / and '/') in the same function as in Flask, but using Flask-RESTful.
Similar questions:
Catch-All URL in flask-restful The Asker does not want to catch / or at least not in the same functions as other URL-s.
Flask restful API urls The Answerer proposes two classess as two resources. I have to initialize the class through resource_class_kwargs keyword argument and I want to keep only one instance, so it will not be good for me.
What I've tried:
Create two add_resource calls for the same class. It end with error.
Debug add_resource. It shows that it creates a resource view function from the Endpoint and that is given to the add_url_rule function. Else it works the same as the two subsequent add_url_rule functions.
By trial and error I've figured out the solution, which is neither documented nor looks like to the expected way of doing it (simmilarly as in Flask, showed in the question).
One must supply a Pythonic default argument to get() and other functions: get(stuff='DEF_VAL')
Full example which is working:
from flask import Flask
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
class RESTapp(Resource):
#staticmethod
def get(path=''): # <-- You should provide the default here not in api.add_resource()!
return 'You want path: \'%s\'' % path # do get something
api.add_resource(RESTapp, '/', '/<path:path>') # Here just the URLs must be the arguments!
if __name__ == '__main__':
app.run()

Flask: Trouble Accessing View (URL not found on server)

I'm trying to add another view to my Flask app. My app/views.py looks like this:
from flask import render_template
from app import app
from helpfulFunctions import *
def getRankingList():
allPlayers = main()
return allPlayers
def displayLimitedNumberOfPlayers(limit):
allPlayers = main()
allPlayers[0] = limitPlayers(allPlayers[0], limit)
allPlayers[1] = limitPlayers(allPlayers[1], limit)
return allPlayers
#app.route("/")
#app.route("/index")
def index():
rankingList = getRankingList()
return render_template('index.html', title='Home', rankingList = rankingList)
#app.route("/top100")
def top100():
rankingList = displayLimitedNumberOfPlayers(100)
return render_template('top100.html', rankingList = rankingList)
if __name__ == '__main__':
app.run(debug=True)
I've tried to mimic how the Miguel Grinberg tutorial defines routes for / and for /index. I've created a view called top100.html in my templates folder, where the "index.html" file also lives. However, when I try to hit localhost:5000/top100.html, I get:
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
So it seems like Flask doesn't think that URL has a view associated with it...but I'm not sure why.
Any idea?
Thanks for the help,
bclayman
There is no view top100.html in your code.You can do either of these
localhost:5000/top100
OR
change #app.route("/top100") to #app.route("/top100.html")
The route (or url) is specified in the #app.route() definition, so you should visit localhost:5000/top100.
The render_template top100.html is only referenced internally within Flask to specify the template used. Really, this page could be named anything and does not have to be named in any similar way to the route...it just has to match the template file used to build the page served at that url.

Categories