Flask url_for

Flask url_for DEFAULT

Flask – URL Building



The url_for() function is very useful for dynamically building a URL for a specific function. The function accepts the name of a function as first argument, and one or more keyword arguments, each corresponding to the variable part of URL.

The following script demonstrates use of url_for() function.

from flask import Flask, redirect, url_for app = Flask(__name__) @app.route('/admin') def hello_admin(): return 'Hello Admin' @app.route('/guest/<guest>') def hello_guest(guest): return 'Hello %s as Guest' % guest @app.route('/user/<name>') def hello_user(name): if name =='admin': return redirect(url_for('hello_admin')) else: return redirect(url_for('hello_guest',guest = name)) if __name__ == '__main__': app.run(debug = True)

The above script has a function user(name) which accepts a value to its argument from the URL.

The User() function checks if an argument received matches ‘admin’ or not. If it matches, the application is redirected to the hello_admin() function using url_for(), otherwise to the hello_guest() function passing the received argument as guest parameter to it.

Save the above code and run from Python shell.

Open the browser and enter URL as − http://localhost:5000/user/admin

The application response in browser is −

Hello Admin

Enter the following URL in the browser − http://localhost:5000/user/mvl

The application response now changes to −

Hello mvl as Guest
Sours: https://www.tutorialspoint.com/flask/flask_url_building.htm

Flask url_for

Flask url_for

Definition of Flask url_for

Flask url_for is defined as a function that enables developers to build and generate URLs on a Flask application. As a best practice, it is the url_for function that is required to be used, as hard coding the URL in templates and view function of the Flask application tends to utilize more time during modification. If we are using hard coding, and in case we would need to change our URL by inserting another element in the URL, we would have to visit each and every template or form in the code library and make the modifications and will lead to overkill. The url_for function is capable of changing this with just a snap of fingers!

Syntax:

It is time now for us to look into different syntax that is present to url_for function before we even dive into learning the working of url_for. This will help us map the syntaxes to the working methodology so that the learning is more practical and easier to grasp. So, without much further ado, let us get straight into the syntax!

Creating dynamic URL with no key passed:

Note: We need to make sure that the function name doesn’t carry any argument, else it might lead to an error.

Creating dynamic URL with a key and corresponding value passed:

Redirect to a URL using Flask (assuming we are passing key and value pair):

How does url_for work in Flask?

In this section let us go through the working of url_for in Flask, but before that, it is very much required to know about the need for building URL using the reversing function url_for( ). The concept of reversing function is to use meaningful URL to help users. If the web application is able to create a meaningful URL that consists of inputs from users, users may remember the inputs used and will enhance the return to the same page again. Not only this there are other pointers which we will discuss below which signifies the importance of using a dynamic URL, keeping in mind the inputs of the user, instead of hard coding the URL.

  1. Developers can change the content of the URL in one shot, and there is no dependency on remembering locations to manually change the hard-coded URLs.
  2. The process of reversing is more descriptive than hard coding.
  3. The special characters and Unicode data are efficiently handled in case of using dynamic URLs.
  4. This is the easy way to avoid unexpected behavior of relative paths in browsers by allocating absolute paths to the generated URLs.
  5. In the case of an application placed outside URL root, the url_for( ) function is capable of handling such scenarios.

Now that we have an understanding of why url_for( ) is so widely appreciated, we would need to understand the types of View responses, as one of these responses relates to the work of url_for( ). The big 3 ways of route logic, an act of mapping the URLs to their specific actions, are namely generating a page template, providing a response, and redirecting the user to a specified location. The working of url_for( ) falls under the category of redirecting.

The method of redirecting accepts a string and this string is nothing but the path that the user is directed to. For the same, the routes are referred to by their names and not by their URL patterns. In the process of creating this input for the redirect function, we use url_for( ). The function url_for( ) takes the name of the view function as an input and creates an output of the provided view. With the change of route URLs, there will be no broken links between pages. Now, when a view is registered with the @app.route decorator, the endpoint name is determined and is ready to be stored with the route registration. This stored route registration is then used to find all routes which link to the registration with the name along with the parameters passed and then execute them to reveal the output.

One important thing to be kept in mind is that, in case we have registered 2 different functions under the same name, we are bound to get an AssertionError and for the same, we can take the help of the endpoint variable and specify the needful. With this, we complete the working of the url_for( ) function in terms of URL routing.

It’s now time for us to look at the implementation of url_for in a Flask application!

Examples

Now that we have complete knowledge about the implementation of url_for and the working methodology along with a complete view on syntax, in this section, we will try using them in practice so that it is easier to learn them by knowing what the practical output will look like! In the examples, we would look at using test_request_context( ) so that we can realize it on the python shell on what URL the particular command is routed to.

Example #1

Creating dynamic URL with no key passed (Run it on console)

Syntax:

Output:

Flask url_for 1

Example #2

Creating dynamic URL with a key and corresponding value passed

Syntax:

Output:

Flask url_for 2

Here, we can easily see the distinction when 2 different values are passed using parameters

Example #3

Redirect to a URL using Flask (assuming we are passing key and value pair)

Syntax:

Output:

When the type is Premium account type:

example 3

When the type is basic account type:

example 3-1

Conclusion

Herewith in this article, we have got an essence of how URL routing happens and what dynamic URL can bring to the table. With this, we encourage our readers to experiment with notes in the article and build an exciting Flask application!

Recommended Articles

This is a guide to Flask url_for. Here we discuss the definition, How does url_for work in Flask? and examples with code implementation. You may also have a look at the following articles to learn more –

  1. Flask Environment Variables
  2. Flask Session
  3. Python Property()
  4. Python Array Length
Sours: https://www.educba.com/flask-url_for/
  1. Driving duramax with bad injectors
  2. Does harris teeter steam shrimp
  3. Sound of silence meme
  4. Calories in lettuce salad

Python flask.url_for() Examples

The following are 30 code examples for showing how to use flask.url_for(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module flask, or try the search function .

Example 1

def save_session(self, app, session, response): """Save session to Redis.""" domain = self.get_cookie_domain(app) path = url_for('main', _external=False) if not session: self.redis.delete(self.prefix + session.sid) if session.modified: response.delete_cookie(app.session_cookie_name, domain=domain, path=path) else: redis_exp = self.get_redis_expiration_time(app, session) cookie_exp = self.get_expiration_time(app, session) if session.modified: val = self.serializer.dumps(dict(session)) self.redis.setex(self.prefix + session.sid, int(redis_exp.total_seconds()), val) else: self.redis.expire(self.prefix + session.sid, int(redis_exp.total_seconds())) response.set_cookie(app.session_cookie_name, session.sid, expires=cookie_exp, httponly=True, domain=domain, path=path, secure=True)

Example 2

def get_random_edit(): # Check first that we are logged in access_token =flask.session.get('access_token', None) if not access_token: return flask.redirect(flask.url_for('login', next_url=flask.url_for('get_random_edit'))) # Then, redirect to a random cached edit for page_name in list_cache_contents(): # Randomly skip or pick the current one, about 1 % chance. if random() > 0.01: continue cache_fname = "cache/"+to_cache_name(page_name) with open(cache_fname, 'r') as f: page_json = json.load(f) proposed_edits = page_json.get('proposed_edits', []) proposed_edits = [template_edit for template_edit in proposed_edits if (template_edit['classification'] != 'rejected')] if proposed_edits: edit_idx = randint(0, len(proposed_edits)-1) orig_hash = proposed_edits[edit_idx]['orig_hash'] return flask.redirect( flask.url_for('review_one_edit', name=page_name, edit=orig_hash)) return flask.redirect(flask.url_for('index'))

Example 3

def portfolio_main(): transactions = Trades.query.filter_by(user_id=current_user.username) if transactions.count() == 0: return redirect(url_for("main.get_started")) # For now pass only static positions, will update prices and other # data through javascript after loaded. This improves load time # and refresh speed. # Get positions and prepare df for delivery df = positions() df.set_index('trade_asset_ticker', inplace=True) df = df[df['is_currency'] == 0].sort_index(ascending=True) df = df.to_dict(orient='index') if df is None: return redirect(url_for("main.get_started")) return render_template("portfolio.html", title="Portfolio Dashboard", portfolio_data=df)

Example 4

def reset_token(token): if current_user.is_authenticated: return redirect(url_for("main.home")) user = User.verify_reset_token(token) if user is None: flash("That is an invalid or expired token", "warning") return redirect(url_for("users.reset_request")) form = ResetPasswordForm() if form.validate_on_submit(): hash = generate_password_hash(form.password.data) user.password = hash db.session.commit() flash("Your password has been updated! You are now able to log in", "success") return redirect(url_for("users.login")) return render_template("reset_token.html", title="Reset Password", form=form)

Example 5

def test_non_public_depts_display_for_users_with_access(self, testapp): ''' Users can see links to datasets they're allowed to access on the front page ''' impd = Department.create(name="I Police Department", short_name="IMPD", is_public=True) UseOfForceIncidentIMPD.create(department_id=impd.id, opaque_id="12345abcde") bpd = Department.create(name="B Police Department", short_name="BPD", is_public=False) UseOfForceIncidentBPD.create(department_id=bpd.id, opaque_id="12345abcde") lmpd = Department.create(name="LM Police Department", short_name="LMPD", is_public=False) UseOfForceIncidentLMPD.create(department_id=lmpd.id, opaque_id="12345abcde") # A non logged-in user can only see the public department response = testapp.get("/", status=200) soup = BeautifulSoup(response.text, "html.parser") assert soup.find("a", href="/department/IMPD/useofforce") is not None assert soup.find("a", href="/department/BPD/useofforce") is None assert soup.find("a", href="/department/LMPD/useofforce") is None # A user associated with a particular department can see that department's # available datasets when logged in create_and_log_in_user(testapp=testapp, department=bpd, username="user1") response = testapp.get("/", status=200) soup = BeautifulSoup(response.text, "html.parser") assert soup.find("a", href="/department/IMPD/useofforce") is not None assert soup.find("a", href="/department/BPD/useofforce") is not None assert soup.find("a", href="/department/LMPD/useofforce") is None # A user with admin access can see all departments' available datasets create_and_log_in_user(testapp=testapp, department=impd, rolename='admin', username="user2") response = testapp.get("/", status=200) soup = BeautifulSoup(response.text, "html.parser") assert soup.find("a", href="/department/IMPD/useofforce") is not None assert soup.find("a", href="/department/BPD/useofforce") is not None assert soup.find("a", href="/department/LMPD/useofforce") is not None # Log out and only the public department should be visible testapp.get(url_for('public.logout')).follow() response = testapp.get("/", status=200) soup = BeautifulSoup(response.text, "html.parser") assert soup.find("a", href="/department/IMPD/useofforce") is not None assert soup.find("a", href="/department/BPD/useofforce") is None assert soup.find("a", href="/department/LMPD/useofforce") is None

Example 6

def login(): """Initiate an OAuth login. Call the MediaWiki server to get request secrets and then redirect the user to the MediaWiki server to sign the request. """ consumer_token = mwoauth.ConsumerToken( app.config['CONSUMER_KEY'], app.config['CONSUMER_SECRET']) try: redirect, request_token = mwoauth.initiate( app.config['OAUTH_MWURI'], consumer_token) except Exception: app.logger.exception('mwoauth.initiate failed') return flask.redirect(flask.url_for('index')) else: flask.session['request_token'] = dict(zip( request_token._fields, request_token)) return flask.redirect(redirect)

Example 7

def stream_url(): url = flask.request.args.get('url') r = requests.get(url) # If it's just an HTML page served over HTTPS, no problem if url.startswith('https://') and ( 'text/html' in r.headers['Content-Type'] ): return flask.redirect(flask.url_for('redirect_to_url', url=url)) response = flask.make_response() response.data = r.content response.headers['Content-Type'] = r.headers['Content-Type'] # Preserve filename if possible if 'Content-Disposition' in r.headers: response.headers['Content-Disposition'] = r.headers['Content-Disposition'].replace("attachment;", "inline;") # Work around incorrect application/octet-stream if 'zenodo.org' in url: response.headers['Content-Type'] = 'application/pdf' return response

Example 8

def login(): if current_user.is_authenticated: return redirect(url_for("main.home")) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user and check_password_hash(user.password, form.password.data): login_user(user, remember=form.remember.data) # The get method below is actually very helpful # it returns None if empty. Better than using [] for a dictionary. next_page = request.args.get("next") # get the original page if next_page: return redirect(next_page) else: return redirect(url_for("main.home")) else: flash("Login failed. Please check e-mail and password", "danger") return render_template("login.html", title="Login", form=form)

Example 9

def reset_request(): if current_user.is_authenticated: return redirect(url_for("main.home")) form = RequestResetForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() send_reset_email(user) flash( "An email has been sent with instructions to reset your" + " password.", "info", ) return redirect(url_for("users.login")) return render_template("reset_request.html", title="Reset Password", form=form)

Example 10

def delete_baccount(id): # type = account or address account = None type = request.args.get("type") if type == "account": account = AccountInfo.query.filter_by( user_id=current_user.username).filter_by(account_id=id) if type == "address": account = BitcoinAddresses.query.filter_by( user_id=current_user.username).filter_by(address_id=id) if (account is None) or (account.count() == 0): flash(f"{type.capitalize()} id: {id} not found. Nothing done.", "warning") return redirect(url_for("node.bitcoin_monitor")) if account.first().user_id != current_user.username: abort(403) account.delete() db.session.commit() flash(f"{type.capitalize()} deleted", "danger") return redirect(url_for("node.bitcoin_monitor"))

Example 11

def get_user_posts(id): user = User.query.get_or_404(id) page = request.args.get('page', 1, type=int) pagination = user.posts.order_by(Post.timestamp.desc()).paginate( page, per_page=current_app.config['CIRCULATE_POSTS_PER_PAGE'], error_out=False) posts = pagination.items prev = None if pagination.has_prev: prev = url_for('api.get_user_posts', page=page-1, _external=True) next = None if pagination.has_next: next = url_for('api.get_user_posts', page=page+1, _external=True) return jsonify({ 'posts': [post.to_json() for post in posts], 'prev': prev, 'next': next, 'count': pagination.total })

Example 12

def get_user_followed_posts(id): user = User.query.get_or_404(id) page = request.args.get('page', 1, type=int) pagination = user.followed_posts.order_by(Post.timestamp.desc()).paginate( page, per_page=current_app.config['CIRCULATE_POSTS_PER_PAGE'], error_out=False) posts = pagination.items prev = None if pagination.has_prev: prev = url_for('api.get_user_followed_posts', page=page-1, _external=True) next = None if pagination.has_next: next = url_for('api.get_user_followed_posts', page=page+1, _external=True) return jsonify({ 'posts': [post.to_json() for post in posts], 'prev': prev, 'next': next, 'count': pagination.total })

Example 13

def get_comments(): page = request.args.get('page', 1, type=int) pagination = Comment.query.order_by(Comment.timestamp.desc()).paginate( page, per_page=current_app.config['CIRCULATE_COMMENTS_PER_PAGE'], error_out=False) comments = pagination.items prev = None if pagination.has_prev: prev = url_for('api.get_comments', page=page-1, _external=True) next = None if pagination.has_next: next = url_for('api.get_comments', page=page+1, _external=True) return jsonify({ 'comments': [comment.to_json() for comment in comments], 'prev': prev, 'next': next, 'count': pagination.total })

Example 14

def get_post_comments(id): post = Post.query.get_or_404(id) page = request.args.get('page', 1, type=int) pagination = post.comments.order_by(Comment.timestamp.asc()).paginate( page, per_page=current_app.config['CIRCULATE_COMMENTS_PER_PAGE'], error_out=False) comments = pagination.items prev = None if pagination.has_prev: prev = url_for('api.get_post_comments', page=page-1, _external=True) next = None if pagination.has_next: next = url_for('api.get_post_comments', page=page+1, _external=True) return jsonify({ 'comments': [comment.to_json() for comment in comments], 'prev': prev, 'next': next, 'count': pagination.total })

Example 15

def password_reset_request(): if not current_user.is_anonymous: return redirect(url_for('main.index')) form = PasswordResetRequestForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: token = user.generate_reset_token() send_email(user.email, 'Reset Your Password', 'auth/email/reset_password', user=user, token=token, next=request.args.get('next')) flash('An email with instructions to reset your password has been ' 'sent to you.') return redirect(url_for('auth.login')) return render_template('auth/reset_password.html', form=form)

Example 16

def test_users(self): # add two users r = Role.query.filter_by(name='User').first() self.assertIsNotNone(r) u1 = User(email='[email protected]', username='john', password='cat', confirmed=True, role=r) u2 = User(email='[email protected]', username='susan', password='dog', confirmed=True, role=r) db.session.add_all([u1, u2]) db.session.commit() # get users response = self.client.get( url_for('api.get_user', id=u1.id), headers=self.get_api_headers('[email protected]', 'dog')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertTrue(json_response['username'] == 'john') response = self.client.get( url_for('api.get_user', id=u2.id), headers=self.get_api_headers('[email protected]', 'dog')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertTrue(json_response['username'] == 'susan')

Example 17

def get_url(self): return url_for('get_device', id=self.id, _external=True)

Example 18

def get_url(self): return url_for('get_device', id=self.id, _external=True)

Example 19

def get_calendar_token(id_sec: str, semester: str): """ :param id_sec: 加密后的学号或教工号 :param semester: 学期,如 2018-2019-1 错误码: 4000 请求无效 4003 无权访问 """ try: res_type, res_id = encryption.decrypt(id_sec) except ValueError: return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, '用户ID无效') if res_type == encryption.RTYPE_STUDENT: if not user_service.has_access(res_id, g.username)[0]: return generate_error_response(None, api_helpers.STATUS_CODE_PERMISSION_DENIED, '无权访问该用户课表') student = entity_service.get_student_timetable(res_id, semester) if not student: return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, '学生不存在') token = calendar_service.get_calendar_token(resource_type=res_type, identifier=student.student_id, semester=semester) else: teacher = entity_service.get_teacher_timetable(res_id, semester) if not teacher: return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, '教师不存在') token = calendar_service.get_calendar_token(resource_type=res_type, identifier=teacher.teacher_id, semester=semester) ics_url = url_for('calendar.ics_download', calendar_token=token, _external=True) ics_webcal = ics_url.replace('https', 'webcal').replace('http', 'webcal') return generate_success_response({'token': token, 'ics_url': ics_url, 'ics_url_webcal': ics_webcal})

Example 20

def register_choice(): """注册:第二步:选择注册方式""" if not session.get(SESSION_USER_REGISTERING, None): # 步骤异常,跳回第一步 return redirect(url_for('user.register')) return render_template('user/registerChoice.html')

Example 21

def register_by_password_status(): """AJAX 刷新教务验证状态""" if not request.args.get("request", None) or not isinstance(request.args["request"], str): return "Invalid request" try: success, message, identifier = user_service.register_by_password_status_refresh(request.args.get("request")) if success: # write login state to session flash(MSG_REGISTER_SUCCESS) if SESSION_PWD_VER_REQ_ID in session: del session[SESSION_PWD_VER_REQ_ID] _set_current_user(identifier) # potential uncaught error return jsonify({"message": "SUCCESS"}) elif message in ("PASSWORD_WRONG", "INTERNAL_ERROR", "INVALID_REQUEST_ID"): return jsonify({"message": message}) else: return jsonify({"message": "NEXT_TIME"}) except everyclass.server.user.exceptions.IdentityVerifyRequestNotFoundError: return "Invalid request" except user_service.IdentityVerifyMethodNotExpectedError: return "Invalid request" except everyclass.server.user.exceptions.AlreadyRegisteredError: # 已经注册成功,但不知为何(可能是网络原因)进入了中间状态,没有执行下面的删除 session 的代码,并且用户刷新页面 if SESSION_PWD_VER_REQ_ID in session: del session[SESSION_PWD_VER_REQ_ID] flash(MSG_ALREADY_REGISTERED) return redirect(url_for('user.login'))

Example 22

def register_by_password_success(): """验证成功后跳转到用户首页""" return redirect(url_for("user.main"))

Example 23

def logout(): """用户退出登录""" del session[SESSION_CURRENT_USER] flash("退出登录成功。") return redirect(url_for('main.main'))

Example 24

def applications(token, action): ts = current_app.config["USTS"] max_age = current_app.config["USTS_MAX_AGE"] try: owner, project = ts.loads(token, max_age=max_age) except SignatureExpired: return f"signature for {owner} of {project} expired." try: obj = Projects.objects.get(project=project, owner=owner, is_approved=False) except DoesNotExist: return f"{project} for {owner} already approved or denied." actions = ["approve", "deny"] if action not in actions: response = f"<h3>{project}</h3><ul>" scheme = "http" if current_app.config["DEBUG"] else "https" for a in actions: u = url_for( "projects.applications", token=token, action=a, _scheme=scheme, _external=True, ) response += f'<li><a href="{u}">{a}</a></li>' return response + "</ul>" if action == "approve": obj.is_approved = True obj.save() # post_save (created=False) sends notification when `is_approved` set else: obj.delete() # post_delete signal sends notification return f'{project} {action.replace("y", "ie")}d and {owner} notified.'

Example 25

def signup(): """ Sign-up form to create new user accounts. GET: Serve sign-up page. POST: Validate form, create account, redirect user to dashboard. """ form = SignupForm() if form.validate_on_submit(): existing_user = User.query.filter_by(email=form.email.data).first() if existing_user is None: user = User( name=form.name.data, email=form.email.data, website=form.website.data ) user.set_password(form.password.data) db.session.add(user) db.session.commit() # Create new user login_user(user) # Log in as newly created user print(user) return redirect(url_for('main_bp.dashboard')) flash('A user already exists with that email address.') return render_template( 'signup.jinja2', title='Create an Account.', form=form, template='signup-page', body="Sign up for a user account." )

Example 26

def login(): """ Log-in page for registered users. GET: Serve Log-in page. POST: Validate form and redirect user to dashboard. """ if current_user.is_authenticated: return redirect(url_for('main_bp.dashboard')) # Bypass if user is logged in form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() # Validate Login Attempt if user and user.check_password(password=form.password.data): login_user(user) next_page = request.args.get('next') return redirect(next_page or url_for('main_bp.dashboard')) flash('Invalid username/password combination') return redirect(url_for('auth_bp.login')) return render_template( 'login.jinja2', form=form, title='Log in.', template='login-page', body="Log in with your User account." )

Example 27

def unauthorized(): """Redirect unauthorized users to Login page.""" flash('You must be logged in to view that page.') return redirect(url_for('auth_bp.login'))

Example 28

def logout(): """User log-out logic.""" logout_user() return redirect(url_for('auth_bp.login'))

Example 29

def start_password_reset(user_id): user = User.get_by_id(user_id) if not user: abort(404) if request.method == 'POST': user.password_reset_uuid = str(uuid.uuid4()) user.save() flash('User password reset engaged.', 'info') return redirect(url_for('admin.edit_user', user_id=user_id)) return redirect(url_for('admin.edit_user', user_id=user_id))

Example 30

def delete_demographic_row(department_id, value_id): department = Department.get_by_id(department_id) value = DemographicValue.get_by_id(value_id) if not department or not value: abort(404) value.delete() return redirect(url_for( 'department.edit_demographics', department_id=department_id ))
Sours: https://www.programcreek.com/python/example/51519/flask.url_for
Using url_for In Flask Templates

flask.helpers url_for Example Code

url_for is function in the Flask module. generates a URL to an endpoint using the method passed in as an argument.

Note that is typically imported directly from instead of from , even though it is defined within the module. It is the same function that is imported, but it's less characters to type when you leave off the part.

flash, get_root_path, make_response, safe_join, and send_file are several other callables with code examples from the same package.

Example 1 from CTFd

CTFd (homepage) is a capture the flag (CTF) hacking web app built with Flask. The application can be used as-is to run CTF events, or modified for custom rules for related scenarios. CTFd is open sourced under the Apache License 2.0.

CTFd / tests / test_views.py

# test_views.pyimportosfromflaskimporturl_forfromfreezegunimportfreeze_timefromCTFd.cacheimportclear_pagesfromCTFd.utilsimportset_configfromCTFd.utils.config.pagesimportget_pagesfromCTFd.utils.encodingimporthexencodefromtests.helpersimport(create_ctfd,destroy_ctfd,gen_challenge,gen_file,gen_page,login_as_user,register_user,)deftest_index():app=create_ctfd()withapp.app_context():withapp.test_client()asclient:r=client.get("/")assertr.status_code==200destroy_ctfd(app)## ... source file abbreviated to get to url_for examples ...register_user(app)client=login_as_user(app)r=client.get("/profile")assertr.status_code==200destroy_ctfd(app)deftest_user_can_access_files():app=create_ctfd()withapp.app_context():fromCTFd.utils.uploadsimportrmdirchal=gen_challenge(app.db)chal_id=chal.idpath=app.config.get("UPLOAD_FOLDER")location=os.path.join(path,"test_file_path","test.txt")directory=os.path.dirname(location)model_path=os.path.join("test_file_path","test.txt")try:os.makedirs(directory)withopen(location,"wb")asobj:obj.write("testing file load".encode())gen_file(app.db,location=model_path,challenge_id=chal_id)url=url_for("views.files",path=model_path)set_config("challenge_visibility","public")withapp.test_client()asclient:r=client.get(url)assertr.status_code==200assertr.get_data(as_text=True)=="testing file load"set_config("challenge_visibility","private")withapp.test_client()asclient:r=client.get(url)assertr.status_code==403assertr.get_data(as_text=True)!="testing file load"register_user(app)client=login_as_user(app)r=client.get(url)assertr.status_code==200assertr.get_data(as_text=True)=="testing file load"withfreeze_time("2017-10-5"):set_config("start","1507262400")forvin("public","private"):## ... source file abbreviated to get to url_for examples ...finally:rmdir(directory)destroy_ctfd(app)deftest_user_can_access_files_with_auth_token():app=create_ctfd()withapp.app_context():fromCTFd.utils.uploadsimportrmdirchal=gen_challenge(app.db)chal_id=chal.idpath=app.config.get("UPLOAD_FOLDER")md5hash=hexencode(os.urandom(16))location=os.path.join(path,md5hash,"test.txt")directory=os.path.dirname(location)model_path=os.path.join(md5hash,"test.txt")try:os.makedirs(directory)withopen(location,"wb")asobj:obj.write("testing file load".encode())gen_file(app.db,location=model_path,challenge_id=chal_id)url=url_for("views.files",path=model_path)register_user(app)withlogin_as_user(app)asclient:req=client.get("/api/v1/challenges/1")data=req.get_json()file_url=data["data"]["files"][0]withapp.test_client()asclient:r=client.get(url)assertr.status_code==403assertr.get_data(as_text=True)!="testing file load"r=client.get(url_for("views.files",path=model_path,token="random_token_that_shouldnt_work",))assertr.status_code==403assertr.get_data(as_text=True)!="testing file load"r=client.get(file_url)assertr.status_code==200assertr.get_data(as_text=True)=="testing file load"set_config("challenge_visibility","admins")r=client.get(file_url)assertr.status_code==403assertr.get_data(as_text=True)!="testing file load"set_config("challenge_visibility","private")withfreeze_time("2017-10-5"):set_config("start","1507262400")r=client.get(file_url)assertr.status_code==403assertr.get_data(as_text=True)!="testing file load"## ... source file continues with no further url_for examples...

Example 2 from Flask AppBuilder

Flask-AppBuilder (documentation and example apps) is a web application generator that uses Flask to automatically create the code for database-driven applications based on parameters set by the user. The generated applications include default security settings, forms, and internationalization support.

Flask App Builder is provided under the BSD 3-Clause "New" or "Revised" license.

Flask AppBuilder / flask_appbuilder / menu.py

# menu.pyfromtypingimportListfromflaskimportcurrent_app,url_forfromflask_babelimportgettextas__from.apiimportBaseApi,exposefrom.basemanagerimportBaseManagerfrom.security.decoratorsimportpermission_name,protectclassMenuItem(object):def__init__(self,name,href="",icon="",label="",childs=None,baseview=None,cond=None):self.name=nameself.href=hrefself.icon=iconself.label=labelself.childs=childsor[]self.baseview=baseviewself.cond=conddefshould_render(self)->bool:returnbool(self.cond())ifself.condisnotNoneelseTruedefget_url(self):ifnotself.href:ifnotself.baseview:return""else:returnurl_for(f"{self.baseview.endpoint}.{self.baseview.default_view}")else:try:returnurl_for(self.href)exceptException:returnself.hrefdef__repr__(self):returnself.nameclassMenu(object):def__init__(self,reverse=True,extra_classes=""):self.menu=[]ifreverse:extra_classes=extra_classes+"navbar-inverse"[email protected](self):return"navbar-inverse"inself.extra_classesdefget_list(self):returnself.menudefget_flat_name_list(self,menu:"Menu"=None,result:List=None)->List:menu=menuorself.menuresult=resultor[]## ... source file continues with no further url_for examples...

Example 3 from FlaskBB

FlaskBB (project website) is a Flask-based forum web application. The web app allows users to chat in an open message board or send private messages in plain text or Markdown.

FlaskBB is provided as open source under this license.

FlaskBB / flaskbb / markup.py

# markup.pyimportloggingimportreimportmistunefromflaskimporturl_forfrommarkupsafeimportMarkupfrompluggyimportHookimplMarkerfrompygmentsimporthighlightfrompygments.formattersimportHtmlFormatterfrompygments.lexersimportget_lexer_by_namefrompygments.utilimportClassNotFoundimpl=HookimplMarker('flaskbb')logger=logging.getLogger(__name__)_re_user=re.compile(r'@(\w+)',re.I)defuserify(match):value=match.group(1)user="<a href='{url}'>@{user}</a>".format(url=url_for("user.profile",username=value,_external=False),user=value)returnuserclassFlaskBBRenderer(mistune.Renderer):def__init__(self,**kwargs):super(FlaskBBRenderer,self).__init__(**kwargs)defparagraph(self,text):text=_re_user.sub(userify,text)returnsuper(FlaskBBRenderer,self).paragraph(text)defblock_code(self,code,lang):iflang:try:lexer=get_lexer_by_name(lang,stripall=True)exceptClassNotFound:lexer=Noneelse:lexer=Noneifnotlexer:## ... source file continues with no further url_for examples...

Example 4 from flask-base

flask-base (project documentation) provides boilerplate code for new Flask web apps. The purpose of the boilerplate is to stitch together disparate libraries that are commonly used in Flask projects, such as Redis for fast caching and transient data storage, SendGrid for transactional email, SQLAlchemy for persistent data storage through a relational database backend, Flask-WTF for form handling and many others.

flask-base is provided as open source under the MIT license.

flask-base / app / utils.py

# utils.pyfromflaskimporturl_forfromwtforms.fieldsimportFieldfromwtforms.widgetsimportHiddenInputfromwtforms.compatimporttext_typedefregister_template_utils(app):@app.template_test()defequalto(value,other):[email protected]_global()defis_hidden_field(field):fromwtforms.fieldsimportHiddenFieldreturnisinstance(field,HiddenField)app.add_template_global(index_for_role)defindex_for_role(role):returnurl_for(role.index)classCustomSelectField(Field):widget=HiddenInput()def__init__(self,label='',validators=None,multiple=False,choices=[],allow_custom=True,**kwargs):super(CustomSelectField,self).__init__(label,validators,**kwargs)self.multiple=multipleself.choices=choicesself.allow_custom=allow_customdef_value(self):returntext_type(self.data)ifself.dataisnotNoneelse''defprocess_formdata(self,valuelist):ifvaluelist:self.data=valuelist[1]self.raw_data=[valuelist[1]]else:self.data=''## ... source file continues with no further url_for examples...

Example 5 from flask-bones

flask-bones (demo) is large scale Flask example application built with Blueprints (example Blueprint code). This project is provided as open source under the MIT license.

flask-bones / app / utils.py

# utils.pyfromflaskimportrequest,url_fordefurl_for_other_page(**kwargs):url_for_args=request.args.copy()if'pjax'inurl_for_args:url_for_args.pop('_pjax')forkey,valueinkwargs.items():url_for_args[key]=valuereturnurl_for(request.endpoint,**url_for_args)## ... source file continues with no further url_for examples...

Example 6 from Flask-Bootstrap

flask-bootstrap (PyPI package information) makes it easier to use the Bootstrap CSS framework in your Flask applications with less boilerplate code. The project was primarily created by Marc Brinkmann @mbr and the source code is open sourced under the Apache 2.0 license.

Flask-Bootstrap / flask_bootstrap / init.py

# __init__.pyimportrefromflaskimportBlueprint,current_app,url_fortry:fromwtforms.fieldsimportHiddenFieldexceptImportError:defis_hidden_field_filter(field):raiseRuntimeError('WTForms is not installed.')else:defis_hidden_field_filter(field):returnisinstance(field,HiddenField)from.formsimportrender_form__version__='3.3.7.1.dev1'BOOTSTRAP_VERSION=re.sub(r'^(\d+\.\d+\.\d+).*',r'\1',__version__)JQUERY_VERSION='1.12.4'HTML5SHIV_VERSION='3.7.3'RESPONDJS_VERSION='1.4.2'classCDN(object):defget_resource_url(self,filename):raiseNotImplementedErrorclassStaticCDN(object):def__init__(self,static_endpoint='static',rev=False):self.static_endpoint=static_endpointself.rev=revdefget_resource_url(self,filename):extra_args={}ifself.revandcurrent_app.config['BOOTSTRAP_QUERYSTRING_REVVING']:extra_args['bootstrap']=__version__returnurl_for(self.static_endpoint,filename=filename,**extra_args)classWebCDN(object):def__init__(self,baseurl):self.baseurl=baseurldefget_resource_url(self,filename):returnself.baseurl+filenameclassConditionalCDN(object):def__init__(self,confvar,primary,fallback):self.confvar=confvarself.primary=primaryself.fallback=fallbackdefget_resource_url(self,filename):ifcurrent_app.config[self.confvar]:returnself.primary.get_resource_url(filename)returnself.fallback.get_resource_url(filename)## ... source file continues with no further url_for examples...

Example 7 from flask-debugtoolbar

Flask Debug-toolbar (documentation and PyPI page) is a Flask conversion of the popular Django Debug Toolbar project. This extension creates a sidebar with useful debugging information when you are running a Flask application in development mode. The project is provided as open source under this license.

flask-debugtoolbar / flask_debugtoolbar / toolbar.py

# toolbar.pytry:fromurllib.parseimportunquoteexceptImportError:fromurllibimportunquotefromflaskimporturl_for,current_appfromwerkzeug.utilsimportimport_stringclassDebugToolbar(object):_cached_panel_classes={}def__init__(self,request,jinja_env):self.jinja_env=jinja_envself.request=requestself.panels=[]self.template_context={'static_path':url_for('_debug_toolbar.static',filename='')}self.create_panels()defcreate_panels(self):activated=self.request.cookies.get('fldt_active','')activated=unquote(activated).split(';')forpanel_classinself._iter_panels(current_app):panel_instance=panel_class(jinja_env=self.jinja_env,context=self.template_context)ifpanel_instance.dom_id()inactivated:panel_instance.is_active=Trueself.panels.append(panel_instance)defrender_toolbar(self):context=self.template_context.copy()context.update({'panels':self.panels})template=self.jinja_env.get_template('base.html')returntemplate.render(**context)## ... source file continues with no further url_for examples...

Example 8 from flask-login

Flask-Login (project documentation and PyPI package) is a Flask extension that provides user session management, which handles common tasks such as logging in and out of a web application and managing associated user session data. Flask-Login is open sourced under the MIT license.

flask-login / flask_login / utils.py

# utils.pyimporthmacfromhashlibimportsha512fromfunctoolsimportwrapsfromwerkzeug.localimportLocalProxyfromwerkzeug.securityimportsafe_str_cmpfromwerkzeug.urlsimporturl_decode,url_encodefromflaskimport(_request_ctx_stack,current_app,request,session,url_for,has_request_context)from._compatimporttext_type,urlparse,urlunparsefrom.configimportCOOKIE_NAME,EXEMPT_METHODSfrom.signalsimportuser_logged_in,user_logged_out,user_login_confirmedcurrent_user=LocalProxy(lambda:_get_user())defencode_cookie(payload,key=None):returnu'{0}|{1}'.format(payload,_cookie_digest(payload,key=key))defdecode_cookie(cookie,key=None):try:payload,digest=cookie.rsplit(u'|',1)ifhasattr(digest,'decode'):digest=digest.decode('ascii')# pragma: no coverexceptValueError:returnifsafe_str_cmp(_cookie_digest(payload,key=key),digest):returnpayloaddefmake_next_param(login_url,current_url):l_url=urlparse(login_url)c_url=urlparse(current_url)if(notl_url.schemeorl_url.scheme==c_url.scheme)and \ (notl_url.netlocorl_url.netloc==c_url.netloc):returnurlunparse(('','',c_url.path,c_url.params,c_url.query,''))returncurrent_urldefexpand_login_view(login_view):iflogin_view.startswith(('https://','http://','/')):returnlogin_viewelse:ifrequest.view_argsisNone:returnurl_for(login_view)else:returnurl_for(login_view,**request.view_args)deflogin_url(login_view,next_url=None,next_field='next'):base=expand_login_view(login_view)ifnext_urlisNone:returnbaseparsed_result=urlparse(base)md=url_decode(parsed_result.query)md[next_field]=make_next_param(base,next_url)netloc=current_app.config.get('FORCE_HOST_FOR_REDIRECTS')or \ parsed_result.netlocparsed_result=parsed_result._replace(netloc=netloc,query=url_encode(md,sort=True))returnurlunparse(parsed_result)deflogin_fresh():returnsession.get('_fresh',False)deflogin_user(user,remember=False,duration=None,force=False,fresh=True):ifnotforceandnotuser.is_active:## ... source file continues with no further url_for examples...

Example 9 from flask-restx

Flask RESTX is an extension that makes it easier to build RESTful APIs into your applications. Flask RESTX aims for minimal configuration to get basic APIs running for existing applications and it exposes endpoint documentation using Swagger.

Flask RESTX is provided as open source under the BSD 3-Clause license.

flask-restx / flask_restx / apidoc.py

# apidoc.pyfrom__future__importunicode_literalsfromflaskimporturl_for,Blueprint,render_templateclassApidoc(Blueprint):def__init__(self,*args,**kwargs):self.registered=Falsesuper(Apidoc,self).__init__(*args,**kwargs)defregister(self,*args,**kwargs):super(Apidoc,self).register(*args,**kwargs)self.registered=Trueapidoc=Apidoc("restx_doc",__name__,template_folder="templates",static_folder="static",static_url_path="/swaggerui",)@apidoc.add_app_template_globaldefswagger_static(filename):returnurl_for("restx_doc.static",filename=filename)defui_for(api):returnrender_template("swagger-ui.html",title=api.title,specs_url=api.specs_url)## ... source file continues with no further url_for examples...

Example 10 from flaskSaaS

flaskSaas is a boilerplate starter project to build a software-as-a-service (SaaS) web application in Flask, with Stripe for billing. The boilerplate relies on many common Flask extensions such as Flask-WTF, Flask-Login, Flask-Admin, and many others. The project is provided as open source under the MIT license.

flaskSaaS / app / views / user.py

# user.pyfromflaskimport(Blueprint,render_template,redirect,request,url_for,abort,flash)fromflask.ext.loginimportlogin_user,logout_user,login_required,current_userfromitsdangerousimportURLSafeTimedSerializerfromappimportapp,models,dbfromapp.formsimportuserasuser_formsfromapp.toolboximportemailimportstripeimportjsonfromjsonimportdumpsstripe_keys={'secret_key':"sk_test_GvpPOs0XFxeP0fQiWMmk6HYe",'publishable_key':"pk_test_UU62FhsIB6457uPiUX6mJS5x"}stripe.api_key=stripe_keys['secret_key']ts=URLSafeTimedSerializer(app.config['SECRET_KEY'])userbp=Blueprint('userbp',__name__,url_prefix='/user')@userbp.route('/signup',methods=['GET','POST'])defsignup():form=user_forms.SignUp()ifform.validate_on_submit():user=models.User(first_name=form.first_name.data,last_name=form.last_name.data,phone=form.phone.data,email=form.email.data,confirmation=False,password=form.password.data,)db.session.add(user)db.session.commit()subject='Please confirm your email address.'token=ts.dumps(user.email,salt='email-confirm-key')confirmUrl=url_for('userbp.confirm',token=token,_external=True)html=render_template('email/confirm.html',confirm_url=confirmUrl)email.send(user.email,subject,html)flash('Check your emails to confirm your email address.','positive')returnredirect(url_for('index'))returnrender_template('user/signup.html',form=form,title='Sign up')@userbp.route('/confirm/<token>',methods=['GET','POST'])defconfirm(token):try:email=ts.loads(token,salt='email-confirm-key',max_age=86400)except:abort(404)user=models.User.query.filter_by(email=email).first()user.confirmation=Truedb.session.commit()flash('Your email address has been confirmed, you can sign in.','positive')returnredirect(url_for('userbp.signin'))@userbp.route('/signin',methods=['GET','POST'])defsignin():## ... source file abbreviated to get to url_for examples ...returnredirect(url_for('userbp.signin'))returnrender_template('user/signin.html',form=form,title='Sign in')@userbp.route('/signout')defsignout():logout_user()flash('Succesfully signed out.','positive')returnredirect(url_for('index'))@userbp.route('/account')@login_requireddefaccount():returnrender_template('user/account.html',title='Account')@userbp.route('/forgot',methods=['GET','POST'])defforgot():form=user_forms.Forgot()ifform.validate_on_submit():user=models.User.query.filter_by(email=form.email.data).first()ifuserisnotNone:subject='Reset your password.'token=ts.dumps(user.email,salt='password-reset-key')resetUrl=url_for('userbp.reset',token=token,_external=True)html=render_template('email/reset.html',reset_url=resetUrl)email.send(user.email,subject,html)flash('Check your emails to reset your password.','positive')returnredirect(url_for('index'))else:flash('Unknown email address.','negative')returnredirect(url_for('userbp.forgot'))returnrender_template('user/forgot.html',form=form)@userbp.route('/reset/<token>',methods=['GET','POST'])defreset(token):try:email=ts.loads(token,salt='password-reset-key',max_age=86400)except:abort(404)form=user_forms.Reset()ifform.validate_on_submit():user=models.User.query.filter_by(email=email).first()ifuserisnotNone:user.password=form.password.datadb.session.commit()flash('Your password has been reset, you can sign in.','positive')returnredirect(url_for('userbp.signin'))## ... source file continues with no further url_for examples...

Example 11 from Flask-User

Flask-User (PyPI information and project documentation) is a Flask extension that makes it easier to add custom user account management and authentication to the projects you are building. The extension supports persistent data storage through both relational databases and MongoDB. The project is provided as open source under the MIT license.

Flask-User / flask_user / email_manager.py

# email_manager.pyfromflaskimportrender_template,url_forfromflask_userimportConfigErrorclassEmailManager(object):def__init__(self,app):self.app=appself.user_manager=app.user_managerself.sender_name=self.user_manager.USER_EMAIL_SENDER_NAMEself.sender_email=self.user_manager.USER_EMAIL_SENDER_EMAILifnotself.sender_email:raiseConfigError('Config setting USER_EMAIL_SENDER_EMAIL is missing.')if'@'notinself.sender_email:raiseConfigError('Config setting USER_EMAIL_SENDER_EMAIL is not a valid email address.')defsend_confirm_email_email(self,user,user_email):ifnotself.user_manager.USER_ENABLE_EMAIL:returnifnotself.user_manager.USER_ENABLE_CONFIRM_EMAIL:returnemail=user_email.emailifuser_emailelseuser.emailobject_id=user_email.idifuser_emailelseuser.idtoken=self.user_manager.generate_token(object_id)confirm_email_link=url_for('user.confirm_email',token=token,_external=True)self._render_and_send_email(email,user,self.user_manager.USER_CONFIRM_EMAIL_TEMPLATE,confirm_email_link=confirm_email_link,)defsend_password_changed_email(self,user):ifnotself.user_manager.USER_ENABLE_EMAIL:returnifnotself.user_manager.USER_SEND_PASSWORD_CHANGED_EMAIL:returnuser_or_user_email_object=self.user_manager.db_manager.get_primary_user_email_object(user)email=user_or_user_email_object.emailself._render_and_send_email(email,user,self.user_manager.USER_PASSWORD_CHANGED_EMAIL_TEMPLATE,)defsend_reset_password_email(self,user,user_email):ifnotself.user_manager.USER_ENABLE_EMAIL:returnassertself.user_manager.USER_ENABLE_FORGOT_PASSWORDemail=user_email.emailifuser_emailelseuser.emailtoken=self.user_manager.generate_token(user.id)reset_password_link=url_for('user.reset_password',token=token,_external=True)self._render_and_send_email(email,user,self.user_manager.USER_RESET_PASSWORD_EMAIL_TEMPLATE,reset_password_link=reset_password_link,)defsend_invite_user_email(self,user,user_invitation):ifnotself.user_manager.USER_ENABLE_EMAIL:returnifnotself.user_manager.USER_ENABLE_INVITE_USER:returninvited_by_user=useremail=user_invitation.emailuser=self.user_manager.db_manager.UserClass(email=email)token=self.user_manager.generate_token(user_invitation.id)accept_invitation_link=url_for('user.register',token=token,_external=True)self._render_and_send_email(email,user,self.user_manager.USER_INVITE_USER_EMAIL_TEMPLATE,accept_invitation_link=accept_invitation_link,invited_by_user=invited_by_user,)defsend_registered_email(self,user,user_email,request_email_confirmation):ifnotself.user_manager.USER_ENABLE_EMAIL:returnifnotself.user_manager.USER_SEND_REGISTERED_EMAIL:returnemail=user_email.emailifuser_emailelseuser.emailifrequest_email_confirmation:token=self.user_manager.generate_token(user_email.idifuser_emailelseuser.id)confirm_email_link=url_for('user.confirm_email',token=token,_external=True)else:confirm_email_link=Noneself._render_and_send_email(email,user,self.user_manager.USER_REGISTERED_EMAIL_TEMPLATE,confirm_email_link=confirm_email_link,)defsend_username_changed_email(self,user):ifnotself.user_manager.USER_ENABLE_EMAIL:returnifnotself.user_manager.USER_SEND_USERNAME_CHANGED_EMAIL:returnuser_or_user_email_object=self.user_manager.db_manager.get_primary_user_email_object(user)email=user_or_user_email_object.emailself._render_and_send_email(email,user,self.user_manager.USER_USERNAME_CHANGED_EMAIL_TEMPLATE,)## ... source file continues with no further url_for examples...

Example 12 from Flasky

Flasky is a wonderful example application by Miguel Grinberg that he builds while teaching developers how to use Flask in his books and videos. Flasky is open sourced under the MIT license.

Flasky / app / models.py

# models.pyfromdatetimeimportdatetimeimporthashlibfromwerkzeug.securityimportgenerate_password_hash,check_password_hashfromitsdangerousimportTimedJSONWebSignatureSerializerasSerializerfrommarkdownimportmarkdownimportbleachfromflaskimportcurrent_app,request,url_forfromflask_loginimportUserMixin,AnonymousUserMixinfromapp.exceptionsimportValidationErrorfrom.importdb,login_managerclassPermission:FOLLOW=1COMMENT=2WRITE=4MODERATE=8ADMIN=16classRole(db.Model):__tablename__='roles'id=db.Column(db.Integer,primary_key=True)name=db.Column(db.String(64),unique=True)default=db.Column(db.Boolean,default=False,index=True)permissions=db.Column(db.Integer)users=db.relationship('User',backref='role',lazy='dynamic')def__init__(self,**kwargs):super(Role,self).__init__(**kwargs)ifself.permissionsisNone:## ... source file abbreviated to get to url_for examples ...defunfollow(self,user):f=self.followed.filter_by(followed_id=user.id).first()iff:db.session.delete(f)defis_following(self,user):ifuser.idisNone:returnFalsereturnself.followed.filter_by(followed_id=user.id).first()isnotNonedefis_followed_by(self,user):ifuser.idisNone:returnFalsereturnself.followers.filter_by(follower_id=user.id).first()[email protected]_posts(self):returnPost.query.join(Follow,Follow.followed_id==Post.author_id)\ .filter(Follow.follower_id==self.id)defto_json(self):json_user={'url':url_for('api.get_user',id=self.id),'username':self.username,'member_since':self.member_since,'last_seen':self.last_seen,'posts_url':url_for('api.get_user_posts',id=self.id),'followed_posts_url':url_for('api.get_user_followed_posts',id=self.id),'post_count':self.posts.count()}returnjson_userdefgenerate_auth_token(self,expiration):s=Serializer(current_app.config['SECRET_KEY'],expires_in=expiration)returns.dumps({'id':self.id}).decode('utf-8')@staticmethoddefverify_auth_token(token):s=Serializer(current_app.config['SECRET_KEY'])try:data=s.loads(token)except:returnNonereturnUser.query.get(data['id'])def__repr__(self):return'<User %r>'%self.usernameclassAnonymousUser(AnonymousUserMixin):## ... source file abbreviated to get to url_for examples [email protected]_manager.user_loaderdefload_user(user_id):returnUser.query.get(int(user_id))classPost(db.Model):__tablename__='posts'id=db.Column(db.Integer,primary_key=True)body=db.Column(db.Text)body_html=db.Column(db.Text)timestamp=db.Column(db.DateTime,index=True,default=datetime.utcnow)author_id=db.Column(db.Integer,db.ForeignKey('users.id'))comments=db.relationship('Comment',backref='post',lazy='dynamic')@staticmethoddefon_changed_body(target,value,oldvalue,initiator):allowed_tags=['a','abbr','acronym','b','blockquote','code','em','i','li','ol','pre','strong','ul','h1','h2','h3','p']target.body_html=bleach.linkify(bleach.clean(markdown(value,output_format='html'),tags=allowed_tags,strip=True))defto_json(self):json_post={'url':url_for('api.get_post',id=self.id),'body':self.body,'body_html':self.body_html,'timestamp':self.timestamp,'author_url':url_for('api.get_user',id=self.author_id),'comments_url':url_for('api.get_post_comments',id=self.id),'comment_count':self.comments.count()}[email protected]_json(json_post):body=json_post.get('body')ifbodyisNoneorbody=='':raiseValidationError('post does not have a body')returnPost(body=body)db.event.listen(Post.body,'set',Post.on_changed_body)classComment(db.Model):__tablename__='comments'id=db.Column(db.Integer,primary_key=True)body=db.Column(db.Text)body_html=db.Column(db.Text)timestamp=db.Column(db.DateTime,index=True,default=datetime.utcnow)disabled=db.Column(db.Boolean)author_id=db.Column(db.Integer,db.ForeignKey('users.id'))post_id=db.Column(db.Integer,db.ForeignKey('posts.id'))@staticmethoddefon_changed_body(target,value,oldvalue,initiator):allowed_tags=['a','abbr','acronym','b','code','em','i','strong']target.body_html=bleach.linkify(bleach.clean(markdown(value,output_format='html'),tags=allowed_tags,strip=True))defto_json(self):json_comment={'url':url_for('api.get_comment',id=self.id),'post_url':url_for('api.get_post',id=self.post_id),'body':self.body,'body_html':self.body_html,'timestamp':self.timestamp,'author_url':url_for('api.get_user',id=self.author_id),}[email protected]_json(json_comment):body=json_comment.get('body')ifbodyisNoneorbody=='':raiseValidationError('comment does not have a body')returnComment(body=body)db.event.listen(Comment.body,'set',Comment.on_changed_body)## ... source file continues with no further url_for examples...

Example 13 from Datadog Flask Example App

The Datadog Flask example app contains many examples of the Flask core functions available to a developer using the web framework.

Datadog Flask Example App / python/flask/app / app.py

# app.pyfromddtraceimportpatch_all;patch_all(flask=True,requests=True)# noqafromddtraceimporttracerfromflaskimportFlask,Responsefromflaskimportafter_this_requestfromflaskimportabort,jsonify,render_template,url_forfromflask.viewsimportViewfromwerkzeug.routingimportRulefromflask_cachingimportCachefromflask_corsimportCORSimportrequestsfrom.blueprintimportbpfrom.exceptionsimportAppExceptionfrom.limiterimportlimiterfrom.signalsimportconnect_signalsapp=Flask(__name__)app.register_blueprint(bp)connect_signals(app)CORS(app)Cache(app,config=dict(CACHE_TYPE='simple'))limiter.init_app(app)## ... source file abbreviated to get to url_for examples [email protected]_requestdefafter_request(response):print('Hook: after_request')[email protected]_requestdefteardown_request(response):print('Hook: teardown_request')[email protected]_appcontextdefteardown_appcontext(appcontext):print('Hook: teardown_appcontext')@app.route('/')@limiter.limit('10 per second')defindex():routes=[dict(rule='GET /',description=['Endpoint for this page, which uses <code>render_template()</code>.'],links=[dict(label='GET /',url=url_for('index')),],),dict(rule='GET /joke',description=['Endpoint which uses <code>requests</code> to fetch a joke from icanhazdadjoke.com.','This endpoint also registers a <code>flask.after_this_request</code> hook.'],links=[dict(label='GET /joke',url=url_for('joke')),],),dict(rule='GET /json',description=['Endpoint which uses <code>jsonify</code> to return a JSON object to the user.',],links=[dict(label='GET /json',url=url_for('json')),],),dict(rule='GET /custom-endpoint/<msg>',description=[('Endpoint which was registered manually using <code>@app.endpoint()</code> ''and <code>app.add_url_rule()</code>'),'This endpoint also has a /custom-endpoint/ url configured with a default <msg>',('We have also attached a @tracer.wrap() to the endpoint and added a ''with tracer.trace(): to the body of the view as well.'),],links=[dict(label='GET /custom-endpoint',url=url_for('custom-endpoint')),dict(label='GET /custom-endpoint/hello',url=url_for('custom-endpoint',msg='hello')),],),dict(rule='GET /custom-error',description=['Endpoint which raises a customer user-defined Exception (non HTTPException)',],links=[dict(label='GET /custom-error',url=url_for('custom_error')),],),dict(rule='GET /stream',description=['Endpoint which uses a generator to stream the response back to the user.',],links=[dict(label='GET /stream',url=url_for('stream')),],),dict(rule='GET /abort/<int:code>',description=['Endpoint which calls <code>abort(code)</code> for us',],links=[dict(label='GET /abort/{}'.format(code),url=url_for('abort_endpoint',code=code))forcodein[400,401,403,404,500]],),dict(rule='GET /hello/<name>',description=['Endpoint which was generated from a <code>flask.views.View</code>',],links=[dict(label='GET /hello/Flask',url=url_for('myview',name='Flask')),],),dict(rule='GET /bp/<name>',description=['Blueprint endpoint that uses <code>render_template_string()</code>',],links=[dict(label='GET /bp/',url=url_for('bp.index')),],),dict(rule='GET /bp/unknown',description=['Blueprint endpoint that calls <code>abort(404)</code>',],links=[dict(label='GET /bp/unkown',url=url_for('bp.unknown')),],),dict(rule='GET /static/test.txt',description=['Endpoint to fetch a simple .txt static file.',],links=[dict(label='GET /static/test.txt',url=url_for('static',filename='test.txt')),],),]returnrender_template('index.jinja2',routes=routes)@app.route('/joke')defjoke():res=requests.get('https://icanhazdadjoke.com/',headers=dict(Accept='text/plain'))res.raise_for_status()@after_this_requestdefafter_joke(response):print('Hook: after_this_request')[email protected]('/json')defjson():returnjsonify(hello='world')## ... source file continues with no further url_for examples...
Sours: https://www.fullstackpython.com/flask-helpers-url-for-examples.html

Url_for flask

Flask URL Building

next →← prev

The url_for() function is used to build a URL to the specific function dynamically. The first argument is the name of the specified function, and then we can pass any number of keyword argument corresponding to the variable part of the URL.

This function is useful in the sense that we can avoid hard-coding the URLs into the templates by dynamically building them using this function.

Consider the following python flask script.

Example

The above script simulates the library management system which can be used by the three types of users, i.e., admin, librarion, and student. There is a specific function named user() which recognizes the user the redirect the user to the exact function which contains the implementation for this particular function.

Flask URL Building

For example, the URL http://localhost:5000/user/admin is redirected to the URL http://localhost:5000/admin, the URL localhost:5000/user/librarion, is redirected to the URL http://localhost:5000/librarion, the URL http://localhost:5000/user/student is redirected to the URL http://localhost/student.

Benefits of the Dynamic URL Building

  1. It avoids hard coding of the URLs.
  2. We can change the URLs dynamically instead of remembering the manually changed hard-coded URLs.
  3. URL building handles the escaping of special characters and Unicode data transparently.
  4. The generated paths are always absolute, avoiding unexpected behavior of relative paths in browsers.
  5. If your application is placed outside the URL root, for example, in /myapplication instead of /, url_for() properly handles that for you.

Next TopicFlask HTTP Methods



← prevnext →



Sours: https://www.javatpoint.com/flask-url-building
Using the url_for Function in Flask

API

rv (Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], WSGIApplication]) –

the return value from the view function. The view function must return a response. Returning , or the view ending without returning, is not allowed. The following types are allowed for :

A response object is created with the string encoded to UTF-8 as the body.

A response object is created with the bytes as the body.

A dictionary that will be jsonify’d before being returned.

Either , , or , where is any of the other types allowed here, is a string or an integer, and is a dictionary or a list of tuples. If is a instance, overwrites the exiting value and are extended.

The object is returned unchanged.

other class

The object is coerced to .

The function is called as a WSGI application. The result is used to create a response object.

Sours: https://flask.palletsprojects.com/api/

Similar news:

Quickstart¶

Eager to get started? This page gives a good introduction to Flask. Follow Installation to set up a project and install Flask first.

A Minimal Application¶

A minimal Flask application looks something like this:

fromflaskimportFlaskapp=Flask(__name__)@app.route("/")defhello_world():return"<p>Hello, World!</p>"

So what did that code do?

  1. First we imported the class. An instance of this class will be our WSGI application.

  2. Next we create an instance of this class. The first argument is the name of the application’s module or package. is a convenient shortcut for this that is appropriate for most cases. This is needed so that Flask knows where to look for resources such as templates and static files.

  3. We then use the decorator to tell Flask what URL should trigger our function.

  4. The function returns the message we want to display in the user’s browser. The default content type is HTML, so HTML in the string will be rendered by the browser.

Save it as or something similar. Make sure to not call your application because this would conflict with Flask itself.

To run the application, use the flask command or python -m flask. Before you can do that you need to tell your terminal the application to work with by exporting the environment variable:

$ export FLASK_APP=hello $ flask run * Running on http://127.0.0.1:5000/
> set FLASK_APP=hello > flask run * Running on http://127.0.0.1:5000/
> $env:FLASK_APP = "hello" > flask run * Running on http://127.0.0.1:5000/

Application Discovery Behavior

As a shortcut, if the file is named or , you don’t have to set the environment variable. See Command Line Interface for more details.

This launches a very simple builtin server, which is good enough for testing but probably not what you want to use in production. For deployment options see Deployment Options.

Now head over to http://127.0.0.1:5000/, and you should see your hello world greeting.

Externally Visible Server

If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer.

If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding to the command line:

$ flask run --host=0.0.0.0

This tells your operating system to listen on all public IPs.

What to do if the Server does not Start¶

In case the python -m flask fails or flask does not exist, there are multiple reasons this might be the case. First of all you need to look at the error message.

Old Version of Flask¶

Versions of Flask older than 0.11 used to have different ways to start the application. In short, the flask command did not exist, and neither did python -m flask. In that case you have two options: either upgrade to newer Flask versions or have a look at Development Server to see the alternative method for running a server.

Invalid Import Name¶

The environment variable is the name of the module to import at flask run. In case that module is incorrectly named you will get an import error upon start (or if debug is enabled when you navigate to the application). It will tell you what it tried to import and why it failed.

The most common reason is a typo or because you did not actually create an object.

Debug Mode¶

The command can do more than just start the development server. By enabling debug mode, the server will automatically reload if code changes, and will show an interactive debugger in the browser if an error occurs during a request.

The interactive debugger in action.

Warning

The debugger allows executing arbitrary Python code from the browser. It is protected by a pin, but still represents a major security risk. Do not run the development server or debugger in a production environment.

To enable all development features, set the environment variable to before calling .

$ export FLASK_ENV=development $ flask run
> set FLASK_ENV=development > flask run
> $env:FLASK_ENV = "development" > flask run

See also:

HTML Escaping¶

When returning HTML (the default response type in Flask), any user-provided values rendered in the output must be escaped to protect from injection attacks. HTML templates rendered with Jinja, introduced later, will do this automatically.

, shown here, can be used manually. It is omitted in most examples for brevity, but you should always be aware of how you’re using untrusted data.

[email protected]("/<name>")defhello(name):returnf"Hello, {escape(name)}!"

If a user managed to submit the name , escaping causes it to be rendered as text, rather than running the script in the user’s browser.

in the route captures a value from the URL and passes it to the view function. These variable rules are explained below.

Routing¶

Modern web applications use meaningful URLs to help users. Users are more likely to like a page and come back if the page uses a meaningful URL they can remember and use to directly visit a page.

Use the decorator to bind a function to a URL.

@app.route('/')defindex():return'Index Page'@app.route('/hello')defhello():return'Hello, World'

You can do more! You can make parts of the URL dynamic and attach multiple rules to a function.

Variable Rules¶

You can add variable sections to a URL by marking sections with . Your function then receives the as a keyword argument. Optionally, you can use a converter to specify the type of the argument like .

[email protected]('/user/<username>')defshow_user_profile(username):# show the user profile for that userreturnf'User {escape(username)}'@app.route('/post/<int:post_id>')defshow_post(post_id):# show the post with the given id, the id is an integerreturnf'Post {post_id}'@app.route('/path/<path:subpath>')defshow_subpath(subpath):# show the subpath after /path/returnf'Subpath {escape(subpath)}'

Converter types:

(default) accepts any text without a slash

accepts positive integers

accepts positive floating point values

like but also accepts slashes

accepts UUID strings

Unique URLs / Redirection Behavior¶

The following two rules differ in their use of a trailing slash.

@app.route('/projects/')defprojects():return'The project page'@app.route('/about')defabout():return'The about page'

The canonical URL for the endpoint has a trailing slash. It’s similar to a folder in a file system. If you access the URL without a trailing slash (), Flask redirects you to the canonical URL with the trailing slash ().

The canonical URL for the endpoint does not have a trailing slash. It’s similar to the pathname of a file. Accessing the URL with a trailing slash () produces a 404 “Not Found” error. This helps keep URLs unique for these resources, which helps search engines avoid indexing the same page twice.

URL Building¶

To build a URL to a specific function, use the function. It accepts the name of the function as its first argument and any number of keyword arguments, each corresponding to a variable part of the URL rule. Unknown variable parts are appended to the URL as query parameters.

Why would you want to build URLs using the URL reversing function instead of hard-coding them into your templates?

  1. Reversing is often more descriptive than hard-coding the URLs.

  2. You can change your URLs in one go instead of needing to remember to manually change hard-coded URLs.

  3. URL building handles escaping of special characters transparently.

  4. The generated paths are always absolute, avoiding unexpected behavior of relative paths in browsers.

  5. If your application is placed outside the URL root, for example, in instead of , properly handles that for you.

For example, here we use the method to try out . tells Flask to behave as though it’s handling a request even while we use a Python shell. See Context Locals.

[email protected]('/')defindex():return'index'@app.route('/login')deflogin():return'login'@app.route('/user/<username>')defprofile(username):returnf'{username}\'s profile'withapp.test_request_context():print(url_for('index'))print(url_for('login'))print(url_for('login',next='/'))print(url_for('profile',username='John Doe'))
/ /login /login?next=/ /user/John%20Doe

HTTP Methods¶

Web applications use different HTTP methods when accessing URLs. You should familiarize yourself with the HTTP methods as you work with Flask. By default, a route only answers to requests. You can use the argument of the decorator to handle different HTTP methods.

[email protected]('/login',methods=['GET','POST'])deflogin():ifrequest.method=='POST':returndo_the_login()else:returnshow_the_login_form()

If is present, Flask automatically adds support for the method and handles requests according to the HTTP RFC. Likewise, is automatically implemented for you.

Static Files¶

Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called in your package or next to your module and it will be available at on the application.

To generate URLs for static files, use the special endpoint name:

url_for('static',filename='style.css')

The file has to be stored on the filesystem as .

Rendering Templates¶

Generating HTML from within Python is not fun, and actually pretty cumbersome because you have to do the HTML escaping on your own to keep the application secure. Because of that Flask configures the Jinja2 template engine for you automatically.

To render a template you can use the method. All you have to do is provide the name of the template and the variables you want to pass to the template engine as keyword arguments. Here’s a simple example of how to render a template:

[email protected]('/hello/')@app.route('/hello/<name>')defhello(name=None):returnrender_template('hello.html',name=name)

Flask will look for templates in the folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package:

Case 1: a module:

/application.py/templates/hello.html

Case 2: a package:

/application/__init__.py/templates/hello.html

For templates you can use the full power of Jinja2 templates. Head over to the official Jinja2 Template Documentation for more information.

Here is an example template:

<!doctype html><title>Hello from Flask</title>{%ifname%}<h1>Hello {{name}}!</h1>{%else%}<h1>Hello, World!</h1>{%endif%}

Inside templates you also have access to the , , and 1 objects as well as the and functions.

Templates are especially useful if inheritance is used. If you want to know how that works, see Template Inheritance. Basically template inheritance makes it possible to keep certain elements on each page (like header, navigation and footer).

Automatic escaping is enabled, so if contains HTML it will be escaped automatically. If you can trust a variable and you know that it will be safe HTML (for example because it came from a module that converts wiki markup to HTML) you can mark it as safe by using the class or by using the filter in the template. Head over to the Jinja 2 documentation for more examples.

Here is a basic introduction to how the class works:

>>> frommarkupsafeimportMarkup>>> Markup('<strong>Hello %s!</strong>')%'<blink>hacker</blink>'Markup('<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')>>> Markup.escape('<blink>hacker</blink>')Markup('&lt;blink&gt;hacker&lt;/blink&gt;')>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()'Marked up \xbb HTML'

Accessing Request Data¶

For web applications it’s crucial to react to the data a client sends to the server. In Flask this information is provided by the global object. If you have some experience with Python you might be wondering how that object can be global and how Flask manages to still be threadsafe. The answer is context locals:

Context Locals¶

Certain objects in Flask are global objects, but not of the usual kind. These objects are actually proxies to objects that are local to a specific context. What a mouthful. But that is actually quite easy to understand.

Imagine the context being the handling thread. A request comes in and the web server decides to spawn a new thread (or something else, the underlying object is capable of dealing with concurrency systems other than threads). When Flask starts its internal request handling it figures out that the current thread is the active context and binds the current application and the WSGI environments to that context (thread). It does that in an intelligent way so that one application can invoke another application without breaking.

So what does this mean to you? Basically you can completely ignore that this is the case unless you are doing something like unit testing. You will notice that code which depends on a request object will suddenly break because there is no request object. The solution is creating a request object yourself and binding it to the context. The easiest solution for unit testing is to use the context manager. In combination with the statement it will bind a test request so that you can interact with it. Here is an example:

fromflaskimportrequestwithapp.test_request_context('/hello',method='POST'):# now you can do something with the request until the# end of the with block, such as basic assertions:assertrequest.path=='/hello'assertrequest.method=='POST'

The other possibility is passing a whole WSGI environment to the method:

withapp.request_context(environ):assertrequest.method=='POST'

The Request Object¶

The request object is documented in the API section and we will not cover it here in detail (see ). Here is a broad overview of some of the most common operations. First of all you have to import it from the module:

fromflaskimportrequest

The current request method is available by using the attribute. To access form data (data transmitted in a or request) you can use the attribute. Here is a full example of the two attributes mentioned above:

@app.route('/login',methods=['POST','GET'])deflogin():error=Noneifrequest.method=='POST':ifvalid_login(request.form['username'],request.form['password']):returnlog_the_user_in(request.form['username'])else:error='Invalid username/password'# the code below is executed if the request method# was GET or the credentials were invalidreturnrender_template('login.html',error=error)

What happens if the key does not exist in the attribute? In that case a special is raised. You can catch it like a standard but if you don’t do that, a HTTP 400 Bad Request error page is shown instead. So for many situations you don’t have to deal with that problem.

To access parameters submitted in the URL () you can use the attribute:

searchword=request.args.get('key','')

We recommend accessing URL parameters with get or by catching the because users might change the URL and presenting them a 400 bad request page in that case is not user friendly.

For a full list of methods and attributes of the request object, head over to the documentation.

File Uploads¶

You can handle uploaded files with Flask easily. Just make sure not to forget to set the attribute on your HTML form, otherwise the browser will not transmit your files at all.

Uploaded files are stored in memory or at a temporary location on the filesystem. You can access those files by looking at the attribute on the request object. Each uploaded file is stored in that dictionary. It behaves just like a standard Python object, but it also has a method that allows you to store that file on the filesystem of the server. Here is a simple example showing how that works:

[email protected]('/upload',methods=['GET','POST'])defupload_file():ifrequest.method=='POST':f=request.files['the_file']f.save('/var/www/uploads/uploaded_file.txt')...

If you want to know how the file was named on the client before it was uploaded to your application, you can access the attribute. However please keep in mind that this value can be forged so never ever trust that value. If you want to use the filename of the client to store the file on the server, pass it through the function that Werkzeug provides for you:

[email protected]('/upload',methods=['GET','POST'])defupload_file():ifrequest.method=='POST':file=request.files['the_file']file.save(f"/var/www/uploads/{secure_filename(file.filename)}")...

For some better examples, see Uploading Files.

Cookies¶

To access cookies you can use the attribute. To set cookies you can use the method of response objects. The attribute of request objects is a dictionary with all the cookies the client transmits. If you want to use sessions, do not use the cookies directly but instead use the Sessions in Flask that add some security on top of cookies for you.

Reading cookies:

[email protected]('/')defindex():username=request.cookies.get('username')# use cookies.get(key) instead of cookies[key] to not get a# KeyError if the cookie is missing.

Storing cookies:

[email protected]('/')defindex():resp=make_response(render_template(...))resp.set_cookie('username','the username')returnresp

Note that cookies are set on response objects. Since you normally just return strings from the view functions Flask will convert them into response objects for you. If you explicitly want to do that you can use the function and then modify it.

Sometimes you might want to set a cookie at a point where the response object does not exist yet. This is possible by utilizing the Deferred Request Callbacks pattern.

For this also see About Responses.

Redirects and Errors¶

To redirect a user to another endpoint, use the function; to abort a request early with an error code, use the function:

fromflaskimportabort,redirect,[email protected]('/')defindex():returnredirect(url_for('login'))@app.route('/login')deflogin():abort(401)this_is_never_executed()

This is a rather pointless example because a user will be redirected from the index to a page they cannot access (401 means access denied) but it shows how that works.

By default a black and white error page is shown for each error code. If you want to customize the error page, you can use the decorator:

[email protected](404)defpage_not_found(error):returnrender_template('page_not_found.html'),404

Note the after the call. This tells Flask that the status code of that page should be 404 which means not found. By default 200 is assumed which translates to: all went well.

See Handling Application Errors for more details.

About Responses¶

The return value from a view function is automatically converted into a response object for you. If the return value is a string it’s converted into a response object with the string as response body, a status code and a text/html mimetype. If the return value is a dict, is called to produce a response. The logic that Flask applies to converting return values into response objects is as follows:

  1. If a response object of the correct type is returned it’s directly returned from the view.

  2. If it’s a string, a response object is created with that data and the default parameters.

  3. If it’s a dict, a response object is created using .

  4. If a tuple is returned the items in the tuple can provide extra information. Such tuples have to be in the form , , or . The value will override the status code and can be a list or dictionary of additional header values.

  5. If none of that works, Flask will assume the return value is a valid WSGI application and convert that into a response object.

If you want to get hold of the resulting response object inside the view you can use the function.

Imagine you have a view like this:

[email protected](404)defnot_found(error):returnrender_template('error.html'),404

You just need to wrap the return expression with and get the response object to modify it, then return it:

[email protected](404)defnot_found(error):resp=make_response(render_template('error.html'),404)resp.headers['X-Something']='A value'returnresp

APIs with JSON¶

A common response format when writing an API is JSON. It’s easy to get started writing such an API with Flask. If you return a from a view, it will be converted to a JSON response.

@app.route("/me")defme_api():user=get_current_user()return{"username":user.username,"theme":user.theme,"image":url_for("user_image",filename=user.image),}

Depending on your API design, you may want to create JSON responses for types other than . In that case, use the function, which will serialize any supported JSON data type. Or look into Flask community extensions that support more complex applications.

[email protected]("/users")defusers_api():users=get_all_users()returnjsonify([user.to_json()foruserinusers])

Sessions¶

In addition to the request object there is also a second object called which allows you to store information specific to a user from one request to the next. This is implemented on top of cookies for you and signs the cookies cryptographically. What this means is that the user could look at the contents of your cookie but not modify it, unless they know the secret key used for signing.

In order to use sessions you have to set a secret key. Here is how sessions work:

fromflaskimportsession# Set the secret key to some random bytes. Keep this really secret!app.secret_key=b'_5#y2L"F4Q8z\n\xec]/'@app.route('/')defindex():if'username'insession:returnf'Logged in as {session["username"]}'return'You are not logged in'@app.route('/login',methods=['GET','POST'])deflogin():ifrequest.method=='POST':session['username']=request.form['username']returnredirect(url_for('index'))return''' <form method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> '''@app.route('/logout')deflogout():# remove the username from the session if it's theresession.pop('username',None)returnredirect(url_for('index'))

How to generate good secret keys

A secret key should be as random as possible. Your operating system has ways to generate pretty random data based on a cryptographic random generator. Use the following command to quickly generate a value for (or ):

$ python -c 'import secrets; print(secrets.token_hex())' '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'

A note on cookie-based sessions: Flask will take the values you put into the session object and serialize them into a cookie. If you are finding some values do not persist across requests, cookies are indeed enabled, and you are not getting a clear error message, check the size of the cookie in your page responses compared to the size supported by web browsers.

Besides the default client-side based sessions, if you want to handle sessions on the server-side instead, there are several Flask extensions that support this.

Message Flashing¶

Good applications and user interfaces are all about feedback. If the user does not get enough feedback they will probably end up hating the application. Flask provides a really simple way to give feedback to a user with the flashing system. The flashing system basically makes it possible to record a message at the end of a request and access it on the next (and only the next) request. This is usually combined with a layout template to expose the message.

To flash a message use the method, to get hold of the messages you can use which is also available in the templates. See Message Flashing for a full example.

Logging¶

Sometimes you might be in a situation where you deal with data that should be correct, but actually is not. For example you may have some client-side code that sends an HTTP request to the server but it’s obviously malformed. This might be caused by a user tampering with the data, or the client code failing. Most of the time it’s okay to reply with in that situation, but sometimes that won’t do and the code has to continue working.

You may still want to log that something fishy happened. This is where loggers come in handy. As of Flask 0.3 a logger is preconfigured for you to use.

Here are some example log calls:

app.logger.debug('A value for debugging')app.logger.warning('A warning occurred (%d apples)',42)app.logger.error('An error occurred')

The attached is a standard logging , so head over to the official docs for more information.

See Handling Application Errors.

Hooking in WSGI Middleware¶

To add WSGI middleware to your Flask application, wrap the application’s attribute. For example, to apply Werkzeug’s middleware for running behind Nginx:

fromwerkzeug.middleware.proxy_fiximportProxyFixapp.wsgi_app=ProxyFix(app.wsgi_app)

Wrapping instead of means that still points at your Flask application, not at the middleware, so you can continue to use and configure directly.

Using Flask Extensions¶

Extensions are packages that help you accomplish common tasks. For example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple and easy to use with Flask.

For more on Flask extensions, see Extensions.

Sours: https://flask.palletsprojects.com/quickstart/


654 655 656 657 658