二手产品经理

二手产品经理

THIS IS RENO

replit auth - 88 Days - Learn Python Online for 100 Days

Record#

  1. Continue learning about replit's Auth feature today. Last time, I learned about using authentication on all pages, and this time it's about authentication on specific pages.
  2. This feature requires importing replit's JavaScript to implement.
  3. Today's coding exercise is to add page authentication to the previous blog. When users log in to the management page, authentication is required.

CODE#

main.py#


from flask import Flask, request, redirect, session
from replit import db
import os
from datetime import datetime

app = Flask(__name__)
app.secret_key = os.environ['sission_key']


@app.route('/', methods=['GET'])
def index():
    #db['user'] = {'name': 'reno', 'pass': '123'}
    uname = request.headers['X-Replit-User-Name']
    if uname != "DengLe":
        print(uname)
        return redirect('/log')
    if session.get('name'):
        text1 = ""
        f = open("index.html", "r")
        page = f.read()
        f.close()
        post = f"""
        <form method="post" action="/">
        <p>Title: <input type="text" name="title"></p>
        <p>Text: <input type="text" name="text"></p>
       <button>submit</button>
      </form>
        """
        for key in db.keys():
            if key and key != "user":
                name = db[key]
                text = f"""
                </hr>
                <h2>{name["title"]}</h2>
                <p>{key}</p>
                <p>{name["text"]}</p>
                """
                text1 += text
        page = page.replace("{text}", text1)
        if uname == "DengLe":
          page = page.replace("{post}", post)
        else:
          page = page.replace("{post}", uname)
        return page
    else:
        return redirect('/log')


@app.route('/', methods=["POST"])
def submit():
    text = request.form
    ttime = datetime.now()
    title = text["title"]
    text = text["text"]
    db[ttime] = {"title": title, "text": text}
    return redirect('/')


@app.route('/log1')
def log1():
    return f"page{session.get('name')}"


@app.route('/log')
def log():
    f = open("login.html", "r")
    page = f.read()
    f.close()

    return page


@app.route('/login', methods=["POST"])
def login():
    user = request.form
    vuser = db['user']
    if vuser['name'] == user["name"] and vuser['pass'] == user["pass"]:
        session["name"] = vuser['name']
        print("--")
        print(session.get('name'))
        print("--")
        return redirect("/")
    else:
        return "NAME OR PASS ERROR!"



app.run(host='0.0.0.0', port=81)


Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.