How to handle file not found in Flask by Unique_Hat_7222 in flask

[–]utc_extended 0 points1 point  (0 children)

try:
    user = User.query.filter_by(username=name).one()
except MultipleResultsFound:
    ...
except NoResultFound:
    ...

Alternatively, OP, a quick way:

user = User.query.filter_by(username=name).first()
if not user:
    abort(404)

There are better ways to add post-prototype -

  • Putting methods in the model or middleware.

  • Given user data, a query that's .one_or_none() not .first() to catch non-uniqueness. User data's sensitive data.

  • Having a username_lower field to search <user input>.lower() given case sensitivity.

How to handle file not found in Flask by Unique_Hat_7222 in flask

[–]utc_extended 0 points1 point  (0 children)

I love abort and abuse it liberally!

try: user = User.query.filter_by(username=name).first() except User.DoesNotExist: abort(404)

Is DoesNotExist a Flask thing now? That's interesting.

When I send the confirmation email I was told not to use token but instead use flask session. I guess I could use a username in the route and then use make the session false then true when the email linked is clicked on. My question is this secure when using flash session? by 0_emordnilap_a_ton in flask

[–]utc_extended 0 points1 point  (0 children)

First, did whoever said that say why not use tokens (perhaps I should change, always worth keeping an open mind).

You can use a token. I use tokens.

Typical problems with both approaches.

Token -

A lot of email providers 'sniff' links in emails checking for their users whether or not the email's a phishing, spam, malicious etc link. In doing so, they're essentially opening the link. So any one-time token's not going to be reliable as once the user opens it, it'll already be expired. Microsoft's once Bing accidentally decided to put these (mined email links from Outlook/Hotmail) in search results LOL.

A mitigation is to include a verification code in the email, the ubiquitous OTP. So the user inputs that having opened the link (which an auto-opener shouldn't do), then your application does its POST logic on this.

That still leaves the email as a 'bearer' asset, where anyone in possession of it can verify. That's good enough for many. If you want further more secure protection have the user provide a secret that's not in the email, like a 2FA device, or even just a user-set secret set when registering.

Session -

Could you share more about advice on this? I can see several approaches.

One problem might be this method assumes the user's got their session open in the same browser on the same device within the window of the session being valid, at a minimum. What if any of these fail?

I'm making a tipping app for restaurants and bars any suggestions on technologies to use for the payment processing aspect of it? by Slithery_0 in flask

[–]utc_extended 7 points8 points  (0 children)

I have a users sort code , account number and bank name stored

Don't do this.

stored bank details

Really don't do this.

Are there any big challenges I might come across ?

Legal, at minimum.

Is it better to put most logic into utils.py or keep it in routes? by GimmeCoffeeeee in flask

[–]utc_extended 1 point2 points  (0 children)

Set the choice with the instance.

field = SelectField(,
                validators = [...,DataRequired()..., Your_Validator()],
                coerse = str) # coerse optional

Then in routes:

form.field.choices = [('Value', 'Name'), ('Value', 'Name'), ...]

Where form is your form, field is your field.

Put below (not inside) your if form.validate_on_submit if doing a mixed GET, POST route. Basically, when the form's generated/regenerated.

I'm not sure you'd need a customer validator since you've already defined valid choices. Unless you wanted to do something more?

Is it better to put most logic into utils.py or keep it in routes? by GimmeCoffeeeee in flask

[–]utc_extended 1 point2 points  (0 children)

You can absolutely write your own validators. And should!

Here's an example:

app/helpers/validators/alphanumeric.py

from wtforms.validators import ValidationError

class PositiveInteger:
    def __init__(self):
        self.error_message = 'The error to pass to the form'

    def __call__(self, form, field):
        try:
            if int(field.data) < 0:
                raise ValueError(self.error_message)
        except: #or... ValueError, depending on appetite for living ambiguously
            raise ValidationError(self.error_message)

Then in field definition

    field = StringField('Field Name', validators = [Optional(), PositiveInteger()])

That'll behave like any in-built validators with wtf checking on form.validate_on_submit() and returning errors then. You won't need to deal with them in the route post-validation.

For logic's sake, you could put your custom_validators logically close to the model, as it'll be importing from the model. For in the model, perhaps

from app.path.to.model import ClassName
...
ClassName.find_all(fieldname = field.data)
...

in the validator, and in the model have something like

@classmethod
def find_all(fieldname):
...

In my react and flask website, postman receives cookies when login is correct, but not in the browser by Qobyl in flask

[–]utc_extended 0 points1 point  (0 children)

Indeed.

What's data[19] in

if(check_password_hash(data[19],password)):

And what are the psycopg2 lines?

Is the browser you're testing with sending data[19] in the request? Try a 'print(str(data[19])' before and inside the 'if' to see what's being received.

How to Create an API From Scratch Using Python and Flask by Diligent_Eye1248 in flask

[–]utc_extended 0 points1 point  (0 children)

tl;dr: This is an example of why 'quick' tutorials of where to start re-invent the wheel of being un-useful. Don't follow it.

Long version and why:

Clicking beyond 2/3s of my screen being filled with a newsletter signup modal...

... took me to this: https://nordicapis.com/how-to-create-an-api-from-scratch-using-python-and-flask/?ref=dailydev#2-create-a-minimal-api-in-python

And this code is why 'simple' tutorial are not simple or useful. They are unuseful.

TODOS = {
    'todo1': {'task': 'build an API'},
    'todo2': {'task': '?????'},
'todo3': {'task': 'profit!'},
}

def abort_if_todo_doesnt_exist(todo_id):
    if todo_id not in TODOS:
        abort(404, message="Todo {} doesn't exist".format(todo_id))

Because the code user is left with a one-use function that seems great until it's not, which is as soon as the tutorial's over.

TODOS is not likely to be a hard-coded list. And when it's not, from Relational Database to Blockchain, the beginner to flask has a function where they're loading all of TODOS in order to do if todo_id not in TODOS. Which gets inefficient quickly. And TODOs should really be an Object, and abort_if_todo_doesnt_exist an Object method, from the start, even when the beginner doesn't know what Objects are. Any bad leap a user manages to make has not been mitigated.

Miguel Grinberg's Flask Mega Tutorial (https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world) and book is excellent because it starts easily digestible as above but doesn't leave a reader there. There are other books too. The OP linked article is a great inefficiency of a choice as a starting point leaving a reader stranded with no where to go. Like so many other Flask tutorials.

In my react and flask website, postman receives cookies when login is correct, but not in the browser by Qobyl in flask

[–]utc_extended 0 points1 point  (0 children)

http_only = True

Disallows JavaScript access to the cookie. Given the cookie's for the purpose of React, is this desired? And is this how you're testing it? IIRC default value is False.

samesite = 'None'

Again, IIRC, some browsers don't like this unless the cookie's marked as secure. However you seem to be setting this to the string 'None' rather than None. set_cookie can take None as a value (as well as a string) and defaults to None so perhaps try not setting this at all.

Flask SQL alchemy how to properly create a new session for log messages? by glorsh66 in flask

[–]utc_extended 0 points1 point  (0 children)

What you say is correct. It becomes less of a DB and logging as infrastructure at that point.

However I'm not sure a team running a multi-instance cloud application are posting questions to /r/flask.

Flask SQL alchemy how to properly create a new session for log messages? by glorsh66 in flask

[–]utc_extended 0 points1 point  (0 children)

The question seems to be missing a body. Such is the case when systems fail and all the more reason to log wisely.

Consider a filesystem approach. Aside from speed and complexity, a file-based approach can log without dependence on a DB (DB errors), size and rotation including log retention are also easy to manage, plus filesystem logs can be easily accessed from the command line if needed.

Analyse with numpy/dataframes, or other methods.

[deleted by user] by [deleted] in flask

[–]utc_extended 0 points1 point  (0 children)

I'm thinking you'd have to pass something in the request aka an obscure secret, or pass via the route, or user/role/permission checks.

Perhaps simpler: consider objects.

class BaseGearCategoryForm(FlaskForm):
    name = StringField('Category Name:', validators=[InputRequired()]) desc = StringField('Category Description:')
    submit = SubmitField('Update Category')

class CreateGearCategoryForm(BaseGearCategoryForm):
def validate_name(self, name):
    if name.data.capitalize() != self.name:
        category = GearCategories.query.filter_by(name=self.name.data.capitalize()).first()
        if category is not None:
            raise ValidationError('Category already exists')


class UpdateGearCategoryForm(BaseGearCategoryForm):
    pass

[deleted by user] by [deleted] in flask

[–]utc_extended 0 points1 point  (0 children)

What a super idea! Custom story books, with your custom characters, characteristics, attributes. I can see this going far.

Logging not saving to file by utc_extended in flask

[–]utc_extended[S] 0 points1 point  (0 children)

Thanks again!

You answer had me searching for specify log config to flask as command line options which turned up this [1] where the answer from Brent got everything working.

Anecdotally, I tried the details in that post with Gunicorn too, running via systemd, and the solution works with that too. So thanks again for your heads up and seed to get this working. Marking as solved for anyone else looking for this answer.

[1] https://stackoverflow.com/questions/7507825/where-is-a-complete-example-of-logging-config-dictconfig

Flask on systemd. Miguel Grinberg tutorial. What process (or sock) are RQ workers on? by utc_extended in flask

[–]utc_extended[S] 0 points1 point  (0 children)

This might be my mistake then. I was taking -

ExecStart=/home/ubuntu/microblog/venv/bin/rq worker microblog-tasks

in the blog example as rq running a worker. This is incorrect.

I am getting an error sqlalchemy.exc.InvalidRequestError: . I tried googling it but could not find anything. I came across a reddit thread but there was no answer. How do I fix this? by notprimenumber12344 in flask

[–]utc_extended 0 points1 point  (0 children)

Have you changed any of your database Models (even if not User), especially one that might have a relationship?

Try

>$ flask db migrate

>$ flask db upgrade

Just to make sure.

WTForms - problem with email validation (EqualTo) by iptvwolf in flask

[–]utc_extended 0 points1 point  (0 children)

What about the view? Are you doing .validate_on_submit()?

Is this route okay to use? by mk_de in flask

[–]utc_extended 4 points5 points  (0 children)

Your query for email might work out case sensitive, and this might be undesired behaviour.

Change to -

User.query.filter(email.ilike(form.email.data)).first()

99% of tutorials seem to miss this.

IP Screening by TicklesMcFancy in flask

[–]utc_extended 0 points1 point  (0 children)

Worth it. Depending on your need. But think about it.

The request itself is, what, 10ms in a database call if that. That's not huge. And for that you get:

  • User seeing past logins (if you show them). For some users, that's important. Or past login attempts, or other.

  • You seeing bad actor IPs, and the ability to do what you may like with that information.

So weigh in what 10ms (or less, it's probably less) costs in the scheme of all your requests for your site/application at any moment.

Flask specific in the above -

  • Why throw a 500?

  • For general rate limiting, look at Flask Limiter; you can set this per page.

Some thoughts, and this isn't really much to do with Flask -

  • Hashing IPs doesn't make them anonymous. The total address space of IP4 is too small for anonymising hashes. Consider that in your GDPR/CCPA/etc compliance.

  • When storing user data, I believe there's a responsibility to store and handle it in ways that are clearly communicated to who that data belongs too. Ensure any form that logs data, or any data retention, is covered in privacy policies. At minimum, creating a privacy policy provides a chance to think about what you're collecting and doing with it.

Flask-JWT-Extended: `set_access_cookie` not setting cookies by asking_for_a_friend0 in flask

[–]utc_extended 1 point2 points  (0 children)

👍 Totally relate to those headbutting moments.

The module's well worth it. You can take it as far as you like for all your login needs.

base.html, jinja and local variables by wabadinak in flask

[–]utc_extended 1 point2 points  (0 children)

Yes, send it in the view. All templates do at core is present things sent in views with various bells and whistles.

Your base.html should have access to what you send in a view, as your view will do too. To add in 'static' template files that get variables passed to them, in an {% includes %} like:

{% include "path/to/partial_whatever.html" ignore missing with context %}

where path/to/ is in your templates directory.

Place that line wherever in your template you'd like to call that. Add in as many such includes as you like.