Home > Blockchain >  Python flask application login
Python flask application login

Time:01-11

I am new to python/flask and started my first project which shows data from a database, for now sqlite, as a searchable table. My problem now is that everyone can edit and add new data to the database since I didn't provide a login (the CRUD works fine). Is there a possibility to add a login without a registration? I just need certain people to have access to the CRUD functionalities and others just to be able to view the table and search in it. These certain ("admin") people also shoulnd't need to register, maybe just type a preset hardcoded name/password to login.

I have tried it with something like this:

@app.route("/")
@app.route("/login",  methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        
        if form.loginname.data == 'admin' and form.loginpassword.data == 'password':
            flash('Logged in!', 'success')
            return redirect(url_for('RetrieveList'))
        else:
            flash('Coulnd't log in!', 'danger')
    return render_template('login.html', title='Login', form=form)

The form:

class LoginForm(FlaskForm):
    loginname = StringField("Name", validators=[InputRequired()])
    loginpassword = PasswordField("Passwort", validators=[InputRequired()])
    
    submit = SubmitField("Log in")

The login.html

<div  style="margin-left: 20px; margin-right: 20px;">
    <form action='' method="POST">
        {{ form.hidden_tag() }}
        <fieldset >
            <legend>Login</legend>
            <div >
                {{ form.loginname.label() }}
                {{ form.loginname() }}
            </div>
            <div >
                {{ form.loginpassword.label() }}
                {{ form.loginpassword() }}
            </div>

            <div >
                {{ form.submit() }}
            </div>
        </fieldset>
    </form>
</div>
<div >
    <small >
        Go to search <a  href="{{ url_for('RetrieveListView') }}">HOME</a>
    </small>

</div>

Retrievelist then has the page with all the functionalities such as "edit/delete/new" in theory but I get the "Method not allowed" error message.

@app.route("/data")
def RetrieveList():
    employees = WissenModel.query.all()
    return render_template("datalist.html", employees=employees)

RetrieveListView has the page without the "edit/delete/new" buttons.

Thanks in advance!

CodePudding user response:

405 (aka Method not allowed) is when you send request with HTTP method that some route are not supposed to handle. When you do not provide methods parameter of route its defaulted by only GET. In your Form:

<form action='' method="POST">

You send POST request to /, but your route:

@app.route("/")
@app.route("/login",  methods=['GET', 'POST'])

Expects only GET under /

To make it work, change your action to /login (or use url_for) or add POST method to / route.

  •  Tags:  
  • Related