r/flask Sep 18 '21

Tutorials and Guides A Compilation of the Best Flask Tutorials for Beginners

328 Upvotes

I have made a list of the best Flask tutorials for beginners to learn web development. Beginners will benefit from it.


r/flask Feb 03 '23

Discussion Flask is Great!

113 Upvotes

I just wanted to say how much I love having a python backend with flask. I have a background in python from machine learning. However, I am new to backend development outside of PHP and found flask to be intuitive and overall very easy to implement. I've already been able to integrate external APIs like Chatgpt into web applications with flask, other APIs, and build my own python programs. Python has been such a useful tool for me I'm really excited to see what flask can accomplish!


r/flask 1h ago

Ask r/Flask Simple Notification Handling Solution

Upvotes

I'm trying to integrate notifications into an existing website structure. Currently on the backend, when I want to create a new notification, I just create a new record in the database and my "sent_to_client" attribute is set to false. On the frontend, I'm using HTMX to create a websocket connection with the server. The problem is that I'm polling the database a couple hundred times a second. I've looked into Redis Pub/Sub models but want to avoid that complexity. I've also used polling in the past but I need data to update much quicker (and reducing the polling time leads to me the same result: - lots of queries).

Is there any workaround to achieve these <1s notifications without the extra complexity and dependencies?

# routes.py

@sock.route("/notifications")
@login_required
def notifications(ws):
    # get initial list of notifications
    all_notifications = Notification.query.filter_by(user_id=current_user.id).filter(Notification.dismissed == False).order_by(Notification.timestamp).all()
    initial_template = render_template("admin/notifications/notifications.html", all_notifications=all_notifications)
    ws.send(initial_template)
    while True:
        # check for new notifications
        new_notifications = Notification.query.filter_by(user_id=current_user.id).filter(Notification.dismissed == False, Notification.sent_to_client == False).order_by(Notification.timestamp).all()
        if new_notifications:
            for notification in new_notifications:
                notification.sent_to_client = True
            db.session.commit()
            template = render_template("admin/notifications/notification.html", all_notifications=new_notifications)
            ws.send(template)
        pass

r/flask 1d ago

Ask r/Flask Flask vs fastapi

14 Upvotes

I am a newbie. I have a little building Web apps in flask but recently came to know about fastapi and how it's more "modern". Now I am confused. I want to start building my career in Web development. Which is better option for me to use? To be more exact, which one is more used in the industry and has a good future? If there isn't much difference then I want to go with whichever is more easier.

P.S: I intend to learn react for front end so even if I


r/flask 1d ago

Show and Tell Working Project: Flask Packages

2 Upvotes

Hello! I've been working on a project firstly names "Flask Packages" (much like Django Packages) the idea is to provide useful information related to projects in the Flask ecosystem, other than to show the project I wanted to ask what information you consider relevant to show in each project, i'm thinking something like this

  • Project:

    • PyPi/Conda api basic information
    • Some sort of "I'm currently using this" button (meh, i don't really want to go the popularity contest road, but it seems logical)
    • Downloads (same as above)
  • Code:

    • repo related information (commit grap, cosed/open issues, etc)
    • Coverage/Tests results?
    • Colaborators?

For now my idea is to categorize each project and then add tags to group them in a way what's useful ("Authorization","Database","Templates", etc)
The repo is at https://github.com/mariofix/limelight in case anyone want to send a pr or start a discussion there.

Let me know what you think (excuse the bootstrap skeleton).
Cheers!


r/flask 1d ago

Ask r/Flask Help needed for setting up a flask webhook

3 Upvotes
from flask import Flask, request
from flask_cors import CORS  

app = Flask(__name__)
CORS(app)

.route('/webhook', methods=['POST'])
def webhook():
    data = request.json  
    print(f"Received data: {data}") 
    return {"message": "Webhook received successfully!"}, 200

if __name__ == '__main__':
    app.run(port=5000)

While running the python/flask script in my mac terminal, I attempted to send a POST request to it via ngrok ("ngrok http 5000" in terminal). I then use curl -X POST to send a /webhook to ngrok, in hopes that it forwards this to my flask. ngrok shows that it received the request, but it encountered a 403 error when trying to forward it to my flask. I retried on Postman, but the same error persisted. I relied a lot on chat gpt, so i suspect theres something wrong with the python code used to run flask (attached above). ChatGPT isnt really helping, (been trying for the past hour and a half lol). Any help is appreciated!!

update: I called a friend and he said the issue was that i was running on port 5000.
"Mac OSX Monterey (12.x) currently uses ports 5000 and 7000 for its Control centre hence the issue. Try running your app from port other than 5000 and 7000"
I changed the port to 8000 and it works now. thank you for your patience r/flask (:


r/flask 2d ago

Ask r/Flask After changing flask port, port 5000 is not working anymore

2 Upvotes

Hey, I was sending API request to my flask application at 192.168.X.X:5000 from my local network for last few days.
Today I asked my friend to try and send API request , because I was in a hurry, I didn't have time to open new ports and I remembered I had port 25565 already opened so I used that one (so it was pub-ip:25565).

Now that I have time, I opened port 5000 and now the script is not working when I go back to port 5000.
I tried again with 25565 and its working, I tried from port 12345 and its working. Just the 5000 is NOT working.
Any suggestions?

FIXED: I just killed what was on port 5000 and its working now

When I start the app:

* Serving Flask app 'main'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://192.168.X.X:5000
Press CTRL+C to quit
* Restarting with stat
* Debugger is active!
* Debugger PIN: 233-951-201

r/flask 4d ago

Ask r/Flask Error while connecting to MySql database in PythonAnywhere.

Thumbnail
gallery
3 Upvotes

r/flask 4d ago

Ask r/Flask Error when trying to use Flask Migrate "Error:no such command 'db'

0 Upvotes

C:\Users\Shimb\Documents\JUKIT_FLASK_PD>flask db init

Error: While importing 'app', an ImportError was raised:

Traceback (most recent call last):

File "C:\Users\Shimb\AppData\Local\Programs\Python\Python311\Lib\site-packages\flask\cli.py", line 245, in locate_app

__import__(module_name)

File "C:\Users\Shimb\Documents\JUKIT_FLASK_PD\app.py", line 3, in <module>

from flask_sqlalchemy import SQLAlchemy

ModuleNotFoundError: No module named 'flask_sqlalchemy'

Usage: flask [OPTIONS] COMMAND [ARGS]...

Try 'flask --help' for help.

Error: No such command 'db'.


r/flask 5d ago

Ask r/Flask Pivot from Flask

5 Upvotes

Hey everyone,

I recently built an app using Flask without realizing it’s a synchronous framework. Because I’m a beginner, I didn’t anticipate the issues I’d face when interacting with multiple external APIs (OpenAI, web crawlers, etc.). Locally, everything worked just fine, but once I deployed to a production server, the asynchronous functions failed since Flask only supports WSGI servers.

Now I need to pivot to a new framework—most likely FastAPI or Next.js. I want to avoid any future blockers and make the right decision for the long term. Which framework would you recommend?

Here are the app’s key features:

  • Integration with Twilio
  • Continuous web crawling, then sending data to an LLM for personalized news
  • Daily asynchronous website crawling
  • Google and Twitter login
  • Access to Twitter and LinkedIn APIs
  • Stripe payments

I’d love to hear your thoughts on which solution (FastAPI or Next.js) offers the best path forward. Thank you in advance!


r/flask 6d ago

Ask r/Flask Volunteer for a google meet

9 Upvotes

Hi ! As the title says, i'm looking for a flask developer to volunteer for an interview through google meet. I teach some university students web development using flask , and i thought it's a good idea to get one of those developers to come into one of our regular meets

You will basically get asked some questions regarding web development, If you are interested, send a PM Anyone's help is much appreciated.

Ps : i'll be happy to answer any questions down below


r/flask 7d ago

Ask r/Flask Where to deploy a flask application ?

11 Upvotes

Hello,

I have a flask app + a script than runs with a crontab to populate data into a database.

I was wondering, is it better to deploy the app on a linux cloud server ? Or should I use a web hosting plateforms that supports flask out of the box ?


r/flask 7d ago

Ask r/Flask Display logs generated by class in flask page in real time

1 Upvotes

I want to display python logs generated when a class is getting executed by taking input from page.i want to display the logs generated as the class is executing in real time in flask page.but the class is getting executed only then the next page with logs is displayed. Any idea how can I display logs in flask page as the class is executing ..


r/flask 7d ago

Ask r/Flask how to authenticate google oauth0 with flask

0 Upvotes

hello gurus i am new bie to flask and vue js how i make my login persistent and i have approach of sending data from frontend request body to backendband backend pull data from db and how to tell front end that i am authenticated and how sgould i persistently login


r/flask 8d ago

Ask r/Flask unable to access config from celery task

1 Upvotes

I am currently working on an app where i need to have scheduled tasks that perform som api calls to external service and store results in a db.

I use Celery to achieve this using this guide https://flask.palletsprojects.com/en/stable/patterns/celery/ , i am able to schedule my tasks but the config containing all the api endpoint details and stuff is empty.

here is my testing code if i instead pass current_app.config in hello_world() the only config variable set is "root_path"

### in app/tasks
from celery import shared_task
from flask import current_app
from app import app, config

@shared_task(ignore_result=False)
def hello_world():
    print(config.__dict__)




### in app/Config.py
    CELERY = dict(
        broker_url="redis://",
        result_backed="redis://",
        task_ignore_result=True,
        imports=('app.tasks',),
        beat_schedule={
            "task-every-10-seconds":{
                "task":"app.tasks.hello_world",
                "schedule": 10},
            "get-all-alarms":{
                "task":"app.tasks.get_all_alarms",
                "schedule": 300
            }}
        )


### app/__init__.py
def celery_init_app(app: Flask) -> Celery:
    class FlaskTask(Task):
        def __call__(self, *args: object, **kwargs: object) -> object:
            with app.app_context():
                return self.run(*args, **kwargs)

    celery_app = Celery(app.name, task_cls=FlaskTask)
    celery_app.config_from_object(app.config["CELERY"])
    celery_app.set_default()
    app.extensions["celery"] = celery_app
    return celery_app



### ./make_celery.py
from app import create_app

flask_app=create_app()
celery_app = flask_app.extensions["celery"]

r/flask 9d ago

Ask r/Flask Where to store passwords in production

12 Upvotes

Hello everyone. I have a flask app i want to deploy on pythonanywhere. In my app i have a function that sends an email and i need to store a password for the email that is a sender. My question is how do i store that password safely when deployed so that i cant be viewed. Also would appreciate if anyone can suggest any other sites for deployment of flask apps. Thanks


r/flask 10d ago

Ask r/Flask What features should all flask apps have?

10 Upvotes

I've been programming for about a year and a half now and built a small flask app to manage my music business. Basically a management application with some API integration and sqlalchemy. The app now works fine and is stable, but I'm wondering if there are any features/functions/etc. that all flask apps should have implemented, that don't seem obvious to a beginner like me. Cybersecurity and complex algorhithms still go a bit beyond my understanding, but I wanna make my app as secure, stable and reliable as possible.


r/flask 10d ago

Ask r/Flask Displaying HTTP response code in Jinja

1 Upvotes

I want to display the response code sent from my Flask backend (e.g. 400 200 201 etc.) in Jinja - how can I access this?


r/flask 10d ago

Ask r/Flask Laravel Developer Inheriting a Flask App

3 Upvotes

Hey all - I've been writing web apps in Laravel pretty much exclusively for the past 10 years. I was hired on by a client who said their previous developer was bailing on them and taking his code with him and I had 3 weeks to recreate his work. I was excited for the challenge. Now they've made nice enough with the previous developer (paying him the $50k of back pay they owed him - red flag!) that he's going to give me the source for the existing app. Turns out it's written in Python/Flask.

They're giving it to me in an AWS AMI that I theoretically just spin up in a new environment and it's good to go - includes all the RabbitMQ stuff, cron jobs, apache setup, etc.

The kicker though is that they want me to sign on to support this thing for a year or more. I was excited about that part too when I thought it was something I was going to write from the ground up and know inside and out. Supporting somebody else's stuff in a stack I don't understand... different enchilada.

Anybody here worked in both Laravel and Flask that might have some insight into what I'm signing myself up for? TIA!


r/flask 11d ago

Ask r/Flask AF

1 Upvotes

My flask code display 'Method Not Found' ,although the "GET" request is working properly . Can any one help me ,please


r/flask 11d ago

Ask r/Flask Flask with apache2 issues with routing.

1 Upvotes

I have a flask app running in a docker container open to port 5000 on my server. Apache2 is proxying port 5000 to myserver.com/myapp (not real). I have used url_for in all my templates however all the addresses it generates go to myserver.com/address instead of myserver.com/myapp/address how do I fix this?


r/flask 12d ago

Ask r/Flask Redirect from a called function

5 Upvotes

let's say I have a route, where the second function is in another file. The redirect is not working.

route
def fun1():
    fun2()

def fun2(): 
    redirect(url_for())

r/flask 12d ago

Discussion Feedback - Cyberbro - Analyze observable (IP, hash, domain) with ease - (CTI Cybersecurity project)

Thumbnail
1 Upvotes

r/flask 13d ago

Ask r/Flask Deploy Flask App

4 Upvotes

Hi everyone, I'm new to web app development and have created a Flask-based application that requests data from a PostgreSQL database, which is then updated on a Vanilla JS-based frontend.

Currently, the application is running on my local Windows environment, and want to publish it so it can be accessed by everyone on the internet. I'm finding it challenging to choose the right path and tools.

My company has a Windows server on Azure. Should deploy the app on an server, or is there a simpler, better approach? Any documentation or tutorials on the recommended deployment path would be very helpful.


r/flask 13d ago

Ask r/Flask Flask-JWT-Extended and "Invalid crypto padding"

1 Upvotes

Hi,

This is my first message on this subreddit.

I've been learning to write backend in Flask for some time now and now I'm trying to familiarize myself with using JWT in it. I have encountered a problem related to the use of the Flask-JWT-Extended library, and more precisely, when I try to send the generated token back, I get the error: "Invalid crypto padding".

It seems to me that token generation is done correctly but I could be wrong, below are some code snippets related to this.

@app.route('/login', methods=['POST'])
def login():
    if request.method == 'POST': return login_controller()
    else:
        return 'Method is Not Allowed'



def login_controller():
    request_form = request.json
    print(request_form)
    password = request_form['password']

    try:
        login = request_form['username']
        user = UserLogin.query.filter(UserLogin.login == login).first()
    except:
        print("User used Email")

    try:
        email = request_form['email']
        print(email)
        user = UserLogin.query.filter(UserLogin.email == email).first()
    except:
        print("User used Username")

    if user and Bcrypt().check_password_hash( user.password, password):
        role = UserProfile.query.filter(UserProfile.user_login_id == user.id).first()
        print(role.role.role_name)
        #, additional_claims={'role': role.role.role_name},
        access_token = create_access_token(identity=user.id )
        return jsonify({'message': 'Login Success', 'access_token': access_token})
    else:
        return jsonify({'message': 'Login Failed'}), 401

The method responsible for checking the token is not finished, because first I wanted to check how to send the token correctly and then I encountered a problem.

@app.route('/checkToken', methods=['GET'])
@jwt_required()
def checkToken():
    if request.method == 'GET': return check_token_controller(get_jwt_identity())
    else:
        return 'Method is Not Allowed'



def check_token_controller(identity):
    print(identity)
    return jsonify({'message': 'Login Failed'}), 401

Below is how I tried to test the method:

Testing the generated token via Postman

Generated token in header:
Authorization: Bearer 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTczNDIwODU1MiwianRpIjoiMTY3MThlZGEtYWVjNy00ZmYwLTlmYTQtMWMwOTA5OWUxZWZmIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6MSwibmJmIjoxNzM0MjA4NTUyLCJjc3JmIjoiY2FlNmE1MWItYjgyYS00MzMwLWFlYTgtNDg2NmNjOGYxM2U5IiwiZXhwIjoxNzM0MjA5NDUyfQ.EwEIJHTJKhETbH0TLty6bqZ4_qUsH4fq-ZLDjuL7Crw'

Response from Postman

I tried to find the answer to the error myself, but unfortunately I can't find a similar error to mine anywhere on the internet. The only thing I could find is that this message means that something is wrong with the token but I don't know what. The token is generated by the same application so all settings must be the same.


r/flask 13d ago

Show and Tell NGL Like project updates.

3 Upvotes

A small update from my NGL like project built with flask and react with following feature.

- Reset password
- New profile & settings design
- Added an email

You can try:
https://stealthmessage.vercel.app/

Send me a message:
https://stealthmessage.vercel.app/secret/c3aec79d0c

Code:
https://github.com/nordszamora/Stealth-Message.git

Send me your feedback:)


r/flask 13d ago

Ask r/Flask How to navigate through file tree using `url_for` with flask buleprint?

1 Upvotes

I'm having trouble making my web app to read static style .css file when using flask blueprint. The HTML fails to read this stylesheet. I'm going describe how the project files are structured followed by the content of each files.

Project structure

Below is the file structure tree:

main.py
coolest_app/
├── __init__.py
└── pages/
    ├── __init__.py
    ├── templates/
    │   ├── base.html
    └── static/
        └── styles/
            └── base.css

There are in total 5 files within this project. But, I'm only giving the content of 4 files only since the .css file content is irrelevant.

a. main.py file

from coolest_app import create_app

app = create_app()

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port="10000")

b. coolest_app/__init__.py file

from flask import Flask


def create_app():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "temporary"

    from .pages import pages
    app.register_blueprint(pages, url_prefix="/")
    return app

c. coolest_app/pages/__init__.py file

from flask import Blueprint, render_template, make_response

pages = Blueprint(
    "pages",
    __name__,
    template_folder="templates",
    static_folder="static",
)


@pages.route("/")
def homepage():
    page = render_template("base.html")
    resp = make_response(page)
    return resp

d. coolest_app/pages/templates/base.html file

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="{{ url_for('static', filename='styles/base.css') }}"/>
    </head>

    <body>
        <h1>Hello, world!</h1>
    </body>
</html>

If anyone knows how to navigate through file tree using url_for(), please help me out 😭. Thank you in advance.