You have multiple options; one of which is to call index2
function from within the index
function:
from flask import Flask, request, make_response
app = Flask(__name__)
@app.route('/')
def index():
if request.authorization.username == 'user1' and request.authorization.password == 'pass1':
index2() # you can return index2() if that's the logged in page.
return '<h1>You are logged in</h1>'
return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})
def index2():
print('In Index2')
if __name__ == '__main__':
app.run(debug=True)
The second option is to differ both functions based on the http method being called:
from flask import Flask, request, make_response
app = Flask(__name__)
@app.route('/')
def index():
if request.authorization.username == 'user1' and request.authorization.password == 'pass1':
return '<h1>You are logged in</h1>'
return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})
@app.route('/', methods=['POST'])
def save():
print('Save operations here')
if __name__ == '__main__':
app.run(debug=True)
The third option is to use different parameters:
from flask import Flask, request, make_response
app = Flask(__name__)
@app.route('/')
def index():
if request.authorization.username == 'user1' and request.authorization.password == 'pass1':
return '<h1>You are logged in</h1>'
return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})
@app.route('/<string:page_name>')
def index2(page_name):
print(f"{page_name}")
if __name__ == '__main__':
app.run(debug=True)
To call index2, try the following quick and dirty code. I'm sure you can improve to have it fit your needs.
@app.route('/')
def index():
if request.authorization and request.authorization.username == 'user1' and request.authorization.password == 'pass1':
return '<h1>You are logged in</h1> <a href="{{ url_for('index2') }}">Click me to go to index2</a>'
return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})
@app.route('/index2')
def index2():
print ('In Index2')
$router - > get('/{home?}', 'SiteController@home') -
> where('home', '(home|another_home_route)') -
> name('home');
Route::match(['get', 'post'], '/user', [
'uses' => 'AppController@user',
'as' => 'useraccess',
'roles' => 'HomeController@useroles',
]);
class HomePageController extends Controller {
function show() {
$classes = Classes::all();
$feeds = Feeds::all();
return view('index', compact('classes', 'feeds'));
}
}
Flask's "Hello world" example defines a route listening at the root our app and executes a view function called home():,Engineer with an ongoing identity crisis. Breaks everything before learning best practices. Completely normal and emotionally stable.,We've seen how to map static and dynamic routes to functions/views using the @app.route() decorator. Flask also empowers us with a number of powerful decorators to supplement the routes we create with .route():,request() is one of the "global" objects we mentioned earlier. It's available to every route and contains all the context of a request made to the said route. Take a look at what things are attached to request which we can access in a route:
from flask
import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello World!"
...
@app.route("/")
@app.route("/home")
@app.route("/index")
def home():
return "Hello World!"
from flask import Flask app = Flask(__name__) @app.route("/api/v1/users/", methods = ['GET', 'POST', 'PUT']) def users(): # Logic goes here
...
@app.route('/user/<username>')
def profile(username):
# Logic goes here
@app.route('/<int:year>/<int:month>/<title>')
def article(year, month, title):
# Logic goes here
from flask
import Flask, render_template
app = Flask(__name__, template_folder = "templates")
from flask
import Flask, render_template
app = Flask(__name__, template_folder = "templates")
@app.route("/")
def home():
""
"Serve homepage template."
""
return render_template("index.html")
Only an authenticated user will be able to access the /dashboard route. We can configure Flask-Login to redirect unauthenticated users to a login page, return an HTTP 401 status or anything else we’d like it to do with them.,@app.route should always be the outermost view decorator.,When you define a route in Flask, you can specify parts of it that will be converted into Python variables and passed to the view function.,Now we can use our converter just like one of the built-ins. We specified the key in the dictionary as “list” so that’s how we use it in @app.route().
@decorator_function
def decorated():
pass
# app.py
from Flask
import render_template
from flask.ext.login
import login_required, current_user
@app.route('/')
def index():
return render_template("index.html")
@app.route('/dashboard')
@login_required
def account():
return render_template("account.html")
# app.py from flask.ext.cache import Cache from flask import Flask app = Flask() # We 'd normally include configuration settings in this call cache = Cache(app) @app.route('/') @cache.cached(timeout = 60) def index(): [...] # Make a few database calls to get the information we need return render_template( 'index.html', latest_posts = latest_posts, recent_users = recent_users, recent_photos = recent_photos )
# myapp / util.py
from functools
import wraps
from datetime
import datetime
from flask
import flash, redirect, url_for
from flask.ext.login
import current_user
def check_expired(func):
@wraps(func)
def decorated_function( * args, ** kwargs):
if datetime.utcnow() > current_user.account_expires:
flash("Your account has expired. Update your billing info.")
return redirect(url_for('account_billing'))
return func( * args, ** kwargs)
return decorated_function
# This code:
@foo
@bar
def one():
pass
r1 = one()
# is the same as this code:
def two():
pass
two = foo(bar(two))
r2 = two()
r1 == r2 # True
# myapp / views.py
from flask
import render_template
from flask.ext.login
import login_required
from.import app
from.util
import check_expired
@app.route('/use_app')
@login_required
@check_expired
def use_app():
""
"Use our amazing app."
""
#[...]
return render_template('use_app.html')
@app.route('/account/billing')
@login_required
def account_billing():
""
"Update your billing info."
""
#[...]
return render_template('account/billing.html')
October 8, 2020 ‐ 1 min read
The code below shows how you use the a function for multiple URLs. In case you're using parameters in one of your routes make sure to provide a default value of the function argument.
@app.route('/chopsticks/')
@app.route('/chopsticks/<int:chopstick_id>')
def chopsticks_view(chopstick_id=None):
if chopstick_id:
return "Chopstick {}".format(chopstick_id)
return "Chopstick list"
Flask Version
$ flask--version Python 3.8 .5 Flask 1.1 .2 Werkzeug 1.0 .1
No, you can't do that. But you can make two completely different people make fun of you.,I want to return two functions at the same time. for example, in regular Python idle: (not including '@app.route('list3'),for example (in flask_app.py):,You need to put {{ processed_text }} on the template where you want it to appear, and make sure you reload the web app and check for typos
@app.route('/list3')
def list3():
a = [1, 2, 3, 4, 5, 6, 7, 8]
b = str(a[::-1])
return b
def hello2():
return 'hello World!'
def double():
return list3(), hello2()
@app.route('/list3')
def list3():
a = [1, 2, 3, 4, 5, 6, 7, 8]
b = str(a[::-1])
return b, 'hello world!'
@app.route('/list3')
def list3():
a = [1, 2, 3, 4, 5, 6, 7, 8]
b = str(a[::-1])
return "{} hello world!".format(b)
return f '{} hello world!'
return f '{b} hello world!'
def my_function(x):
a = 10 * x
b = 20 * x
return a, b