简体   繁体   中英

How do I hash a route in Python Flask?

My goal is pretty simple, I created a route that receives an ID.

@app.route('/afbase/<int:pid>', methods=["GET", "PATCH", "DELETE"])
# We defined the page that will retrieve some info
def show(pid):
    new_person = People.query.filter_by(pid=pid).first()

I don't want this ID to be shown to the final user. How do I hash the route or partially hash the route?

当前网址截图

This route will receive a variable called PID as you can see, this PID variable can be considered as an ID. Not case sensitive but it wouldn't be okay to show on the browser URL.

I tried using hashlib without much success.

You can use the hashids library to encode and decode integer ID's. First, pip install hashids . Then, create a few utility functions.

# utils.py
from flask import current_app
from hashids import Hashids

def create_hashid(id):
    hashids = Hashids(min_length=5, salt=current_app.config['SECRET_KEY'])
    hashid = hashids.encode(id)
    return hashid

def decode_hashid(hashid):
    hashids = Hashids(min_length=5, salt=current_app.config['SECRET_KEY'])
    id = hashids.decode(hashid)
    return id

Next, create a global environment variable so you can call the create_hashid function from your jinja2 template:

# app.py
from utils import create_hashid
app.jinja_env.globals.update(create_hashid=create_hashid)

Here is how to call that function from the link in the template:

# index.html
<a href="{{ url_for('invoice.view_invoice', hashid=create_hashid(invoice.id) ) }}">View Invoice</a>

Finally, your view function:

# views.py
@blueprint.route('/dashboard/invoice/<hashid>')
@login_required
def view_invoice(hashid):
    invoice_id = decode_hashid(hashid)
    invoice = Invoice.query.filter_by(
        user_id=current_user.id,
        id=invoice_id
    ).first_or_404()

return render_template(
    'dashboard/invoice/view_invoice.html',
    invoice=invoice
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM