Thứ Ba, 10 tháng 11, 2020

[Learning] Flask Framework - Python [#2] - Overview





Link [#1] Flask Framework - Python [#1]

Link [#3] Flask Framework - Python [#3]

Continue 

4. Features

COOKIES:

A cookie is just a piece of data which the server sets in the browser. Here is how it works:

~The browser sends the request for a webpage to the server.
~The server responds to the browser request by sending the requested webpage along with one or more cookies.
~Upon receiving the response, the browser renders the webpage and saves the cookie in the user computer.
~The subsequent request to the server will include data from all the cookies in   the Cookie header. This process will continue until the cookie expires. Once    the cookie expires, it is removed from the browser.

- To access cookies you can use the cookies attribute. To set cookies you can use the set_cookie method of response objects. The cookies 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.

- Systax:
set_cookie(key, value="", max_age=None)

The table below show you a list of keys and its value as cookie arguments 



- Set-cookie piece of code:

@app.route('/cookie')
def cookie():
    res = make_response("Setting a cookie")
    res.set_cookie('admin', '4rth4s', max_age = 999999999)
    return res

 Result:



- Setting and getting cookies for login page

@app.route('/auth', methods =['GET', 'POST'])
def auth():
    if request.method=='POST':
        name = request.form['name']
        if name == '4rth4s' and request.form['psw'] == 'admin':
            res = make_response("")
            res.set_cookie('admin', name)
            name = request.cookies.get('admin')
            return '<h1>Welcome ' + name + '</h1>'
            
        else:
            res = make_response('SORRY, YOU ARE NOT ADMIN')
        return res

Result :



+ SESSIONS:

In addition to the request object there is also a second object called session 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.
Flask-Session is a Flask plugin which enables the simple integration of a server-side cache leveraging methods such as Redis, Memcached, MongoDB, relational databases, and so forth. Of these choices, Redis is an exceptionally appealing option.

Redis is NoSQL datastore written in C intended to temporarily hold data in memory for users as they blaze mindlessly through your site. Redis was designed for this very purpose, is extremely quick, and is free to use

- Installation:
pip install flask-session redis

 - Session in Flask:

import os
from flask import Flask, session, redirect, escape, request

app = Flask(__name__)
app.secret_key = os.environ.get('SECRET_KEY', default=None)
SESSION_TYPE = 'filesystem'
app.config.from_object(__name__)
Session(app)

@app.route('/')
def index():
    if 'username' in session:
        return 'Logged in as %s' % escape(session['username'])

    return 'You are not logged in'

@app.route('/auth', methods =['GET', 'POST'])
def auth():
    if request.method=='POST':
        name = request.form['name']
        if name == '4rth4s' and request.form['psw'] == 'admin':
            res = make_response()
            session['name'] = name
            return redirect('/')               
        else:
            res = make_response('SORRY, YOU ARE NOT ADMIN')
        return res





+FLASH MESSAGE
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.
The message will be sent to client in next request, combined with .html file to expose the message

@app.route("/test")
def test():
    flash("This is a flashed message.")
    return render_template('message.html')



+ UPLOAD FILE:

Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to ‘multipart/form-data’, posting the file to a URL. The URL handler fetches file from request.files[] object and saves it to the desired location.

It is possible to define the path of default upload folder and maximum size of uploaded file in configuration settings of Flask object.

Code:

@app.route('/upload')
def upload():
   return render_template('upload.html')
	
@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
   if request.method == 'POST':
      f = request.files['file']
      f.save(f.filename)
      return 'file uploaded successfully' 

HTML :

<html>
   <body>
      <form action = "http://localhost:5000/uploader" method = "POST" 
         enctype = "multipart/form-data">
         <input type = "file" name = "file" />
         <input type = "submit"/>
      </form>
   </body>
</html>


Result




Locate


















Không có nhận xét nào:

Đăng nhận xét

Phổ Biến

Follow by Email