/r/flask

Photograph via snooOG

Flask is a Python micro-framework for web development. Flask is easy to get started with and a great way to build websites and web applications.

Use Python and Flask to build the web faster

Use [Ask Flask] or [AF] if you have a very specific problem and need help with code.

Use [Extension-name] if you are discussing a certain extension to Flask.

Also check out /r/python or /r/django

Websites built with Flask

Getting Started

Flask Hosting

  • PythonAnywhere.com (web-SSH; web-instant-MySQL-db; web-IDE; instant deployment of flask, free; easy logs; github/single-file-upload support; SFTP/SSH requires pay)
  • Heroku (SSH; flask must be installed by you, slightly-difficult-windows-instructions, upgradeable cloud service)
  • WebFaction (SSH; paid-web-host [good prices]; flask must be installed by you; possible configuration and path issues possible; SFTP)
  • Google App Engine (Desktop admin app; flask can be configured with this repo)
  • OpenShift (requires extensive ssh installation of ruby, python, etc.)

Looking for dev jobs?

/r/flask

86,488 Subscribers

3

Flask to Power apps/Power Automate?

Hello, I have made a flask app that runs local with a sqlite3 database, but after the work is done local, I would like to add add this data to sharepoint in a way?

Anyone done anything similar?

0 Comments
2024/11/01
19:29 UTC

11

Any flask github suggestion

I'm currently learning Flaks and i want to improve my quality of code.

Do you have any good repo to look for ?

7 Comments
2024/11/01
18:49 UTC

4

Handling errors with OOP

I'm currentrly trying to create a bank system using OOP with Flask, I wanted that when the if statement that I underlineded in the screenshot goes false, it should redirect the user to a "failure operation" page or something like that.

https://preview.redd.it/mjzdaqgp0cyd1.png?width=509&format=png&auto=webp&s=a0793a592fc091fd2359341d175794c8d1b6a825

https://preview.redd.it/4trn3xte0cyd1.png?width=497&format=png&auto=webp&s=c7cb19bac027aa8111bbf83a6600ccf16022d530

0 Comments
2024/11/01
18:49 UTC

2

What order to upgrade long list of interdependent packages? (Trying to learn Python and Flask)

I've made a web app while learning to code through using Python and Flask. It has been running nicely for a couple of years despite the fact that I have made a bit of a mess of it - for example the virtualenv on the remote server is not identical to the one on my local machine, meaning that a lot of the time when dealing with packages, I have to test things directly on the server, resulting in a crashing website. But that is that.

So I have a list with more than a hundred packages - lots of Flask libraries that are dependent on each other. Now - after having done a million other things with my life for a few years - I'd like to upgrade the packages because I fear that one day Pythonanywhere (with which I'm running the app) will upgrade their OS and I'll have to update Python, causing all the old versions of packages I'm using to crash with an overwhelmingly long list of errors.

I'd like to upgrade the packages one by one or a few at a time because - again - I'm afraid if I use requirements.txt to automatically upgrade everything I'll suddenly have more errors than I can handle and not know how to undo the whole thing.

So I guess my main question is - do I upgrade things that have dependencies before the things they are dependent on, or the other way around? Or is there some clever trick I should know about?

For example: I just tried to upgrade Flask. The site wouldn't run because Flask-User was trying to import from with Jinja2, which was upgraded through Flask and had some changed words. But if I just go on and also upgrade Flask-User, it might trigger a new set of issues and so on. So is there a way - from where I am now - that I can avoid drowning in issues?

7 Comments
2024/10/31
22:30 UTC

13

Upify - quickly deploy Flask apps to the cloud for free

I see a lot of posts in here asking about where to deploy Flask or where to deploy it for free. You can deploy your app to serverless environments, so that it’s not taking up resources if it’s not being used, which should be good for most projects since they don’t get that much traffic. Both AWS Lambda and GCP Cloud Run offer free tiers that should be more than enough for most people to host multiple apps.

Upify is an open source CLI tool, written in Go that makes deploying a Flask app to serverless very easy. It just creates configs and wrappers on top of your existing app. Basically, you have to set up creds for the provider, run a few commands, and you should get back a URL that you can call.

https://github.com/codeupify/upify

https://reddit.com/link/1ggjs87/video/r7tuf4bbk4yd1/player

4 Comments
2024/10/31
17:17 UTC

0

how to connect Dash app to MS SQL database ?

newbie question here, how to connect a dash application to ms sql database so that i can store "permannetly" data ?

Thanks

1 Comment
2024/10/31
13:00 UTC

1

BuildError. werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'payment_table' with values ['total_price']. Did you forget to specify values ['order_no']?

I am getting a build error in my code. order_no and total_price are passed from book_table route to the payment_table route. I tested the variables in the book_table and their values get printed correctly. However, they don't seem to get to the payment_table route.

Flask code is

# Route to process the form submission
@app.route('/book_table', methods=['POST'])
def book_table():
    table_id = "m12"
    user_id = login_session.get('user_id')
    people = request.form.get('people')
    date = request.form.get('date')
    time = request.form.get('time')
    datetime_str = f"{date} {time}"
    table = db.session.query(Table).filter_by(table_id=table_id).first()
    if not table:
        flash("Selected table does not exist.")
        return redirect(url_for('table_booking'))

    total_price = table.reserve_fee * Decimal(people)

    new_booking = Bookings(
        table_id=table_id,
        user_id=user_id,
        book_date_time=datetime_str,
        total_price=total_price
    )
    db.session.add(new_booking)
    db.session.commit()

    last_pay = db.session.query(Pay).order_by(Pay.order_no.desc()).first()
    # Ensure last_pay.order_no defaults to 0 if it's None
    new_order_no = (last_pay.order_no or 0) + 1 if last_pay else 1
    print("Redirecting to payment_table with:", new_order_no, total_price)
    print(type(new_order_no))
    print(type(total_price))

    #return redirect(url_for('payment_table', order_no=new_order_no, total_price=float(total_price))
    return redirect(url_for('payment_table', total_price=float(total_price), order_no=new_order_no))


@app.route('/payment_table/<float:total_price>/<int:order_no>', methods=['GET', 'POST'])
def payment_table(total_price, order_no):
    if request.method == 'POST':
        #if "username" in login_session:
        print("im now in payment table:", order_no, total_price)
        print(type(order_no))
        print(type(total_price))

        cust_name = request.form.get('cardname')
        cust_address = request.form.get('address')
        cust_postcode = request.form.get('postcode')
        cust_email = request.form.get('email')
        cust_cardno = request.form.get('cardnumber')
        card_expirydate = request.form.get('expdate')
        card_cvv = int(request.form.get('cvv'))
        trans_option = request.form.get("trans_option")

        new_pay = Pay(
            order_no=order_no,
            total_price=total_price,
            cust_name=cust_name,
            cust_address=cust_address,
            cust_postcode=cust_postcode,
            cust_email=cust_email,
            cust_cardno=cust_cardno,
            card_expirydate=card_expirydate,
            card_cvv=card_cvv,
            trans_option=trans_option
        )

        db.session.add(new_pay)
        db.session.commit()

        recentp = db.session.query(Pay).order_by(Pay.pay_no.desc()).first()
        return render_template("receipt.html", recentp=recentp)
        print("im here")

    total_price = request.args.get('total_price', '0.0')
    order_no = request.args.get('order_no')
    return render_template("checkout_table.html", total_price=total_price, order_no=order_no)

html code is

<!DOCTYPE html>
<html lang="en">
<head>
    <link
      rel="stylesheet"
      href="{{ url_for('static', filename='styles.css') }}"
    />
</head>
<body>
    <div class="header">
        <h1>Bean & Brew</h1>
        <p>Checkout</p>
    </div>
         <br>
 <form action="{{ url_for('payment_table', order_no=order_no, total_price=total_price) }}" method="POST">
             <br>
             <br>
    <div>
    <h4>Billing Address</h4>
            <label for="fname"><i class="fa fa-user"></i> Full Name</label>
            <input type="text" id="fname" name="firstname" placeholder="John M. Doe"> <br>
            <label for="email"><i class="fa fa-envelope"></i> Email</label>
            <input type="text" id="email" name="email" placeholder="john@example.com"> <br>
            <label for="adr"><i class="fa fa-address-card-o"></i> Address</label>
            <input type="text" id="adr" name="address" placeholder="542 W. 15th Street"> <br>
            <label for="postcode">Postal Code</label>
            <input type="text" id="postcode" name="postcode" placeholder="SN33MC"> <br><br>
    </div>
    <div>
            <label for="cname">Name on Card</label>
            <input type="text" id="cname" name="cardname" placeholder="Susan Smith"> <br>
            <label for="cardno">Credit card number</label>
            <input type="text" id="cardno" name="cardnumber" placeholder="1111-2222-3333-4444"> <br>
            <label for="expdate">Exp Date</label>
            <input type="text" id="expdate" name="expdate" placeholder="02/27"> <br>
            <label for="cvv">CVV</label>
            <input type="text" id="cvv" name="cvv" placeholder="752"> <br> <br> <br>
         </div>
      <p><input type="submit" value="Checkout" /></p>
    </form>
 </body>
</html>
5 Comments
2024/10/31
10:53 UTC

0

Pythonanywhere: AttributeError: 'NoneType' object has no attribute 'cursor'

I want to connect my Flask App with MySQL database, I'm using flask-mysql and I get this error: cursor = mysql.connection.cursor()

AttributeError: 'NoneType' object has no attribute 'cursor', I already did all the checks with users, host and passwords

4 Comments
2024/10/31
02:30 UTC

1

Improve TTFB

Hello,

I’m running into a response time issue with a Flask server in a test setup, and I’m hoping someone might have insights on how to tackle it. The server is set up to handle a pretty large data retrieval task—about 110MB, consisting of around 15,000 rows of complex JSON objects. Flask seems to handle the retrieval and processing reasonably well; it takes about 3 seconds to generate the JSON response. So far, so good.

The problem arises after the data is ready to be sent. I’m seeing a significant delay—around 6 additional seconds—between the endpoint finishing and the start of the response download. This delay feels unusually long, especially given the relatively quick processing time of the data retrieval itself. To troubleshoot, I measured the times directly in the endpoint method and looked at the Time to First Byte (TTFB) using Postman, which confirmed this lag.

I also tried enabling GZIP compression through Flask-Compress, hoping that reducing the response size might help speed things up. However, this didn’t have any effect; the response size stayed roughly the same, and the transmission time didn’t improve.

At this point, I’m not sure what else to try to minimize that 6-second delay. Does anyone have suggestions on what might be causing this or other methods I could use to diagnose and improve the response time? Any help would be greatly appreciated!

Thanks in advance for any insights!

Update:

OK the TTFB does not look like it depends on the response size, rather on the size of the rows.

TTFB (Transfer Start) Size

8.6s 110MB -- 2500 rows with large json data.

7.7s 800KB -- 2500 rows, columns with large dataset removed.

4.1s 63MB -- 1500 rows, with large json data.

1.4s 20MB -- 500 rows, with large json data.

4 Comments
2024/10/30
18:45 UTC

1

Little issue with the flask app I have deployed on DigitalOcean

guys i am using flask Sqlalchemy and flask migrate in my flask app , I have deployed the app on digitalocean(i have made a repo on github and it accesses it from there) and in the console i do flask db init , migrate and update. But like if I make some changes in the code(on github) and upload it again(on digital ocean) then the data in the database of the previous version is lost

what should i do here

20 Comments
2024/10/30
14:24 UTC

1

Receiving Form Data

I am receiving data from 2 html forms on a single page to 2 flask route('/event'), both form contains sensitive info and I don't want to use the GET method for none,

Is it possible for me to use POST for Both?

3 Comments
2024/10/30
10:51 UTC

5

Limited Media Server (Flask + Angular 17)

After the release of Raspberry PI 5 with NVMe support I thought up a project that could utilize the extra storage and speed and enable me to view my content on the GO from my iPhone, iPad or Desktop.

I give you Limited Media Server. I did a preliminary search and nothing showed up under that title, so I'm sticking with it. And I really do use it, behind a WireGuard VPN to view my media (from home) at the office while walking loops in the morning, gotta get those steps in.

Security was a big aspect of this project. I wanted to enable fine grained management encase I want to give my children access to view manga, but limit what they could see. So you can give content a RATING, G, PG, PG13,R.Unrated. And each user has a rating limit, so you could give their account PG-13 access, then put all content not for them under R. The server checks on every rest method to ensure you have the right access rights for the content and the feature used.

Project Parts

Server

  • Pure flask service
  • Plugin support
    • I use it as a test bed, add extra plugins and they show up on restart
    • Plugins actually create processes
    • Plugins can define custom server properties
  • Basic Processing
    • The app has 5 threaded worker.
    • Check the status of processes and see the logs, cancel them
  • Configure it via the website
    • Paths
    • Ports
    • Binding Address
  • View/Manage Manga
    • Bookmark your favorite pages (internal)
  • View/Manage Media files
    • Drop files into folders from your desktop
    • Download from the web
    • Generate previews
    • Bookmark files (internal)
  • Security
    • Content is given a rating, Users have a rating limit that is enforced
    • Users can have a Security Group. Media folders can have a owning Security Group
    • Feature Management (Each user can have the following features)
      • Manage App (Super Admin)
      • Manage Volumes (Manga)
      • Manage Processes
      • Manage Media
      • Use General Plugins
      • Use Utility Plugins
      • Use Volume Plugins
      • Use Media Plugins
      • View Processes
      • View Volumes
      • View Media
      • Bookmarks

Site

  • Angular 17 Standalone project
  • Angular Materials
  • Locally saves your progress for reading manga and can sync to the server
    • Start reading on your iPad and finish on your iPhone
  • Media Browser
    • Media Player, needs more work
    • Stream, Download, Archive, Delete files
  • Management
    • Users
    • Groups
    • Properties
  • Plugin Execution

Thoughts

I did a lot of iterations. Originally I did not have a DB and instead used JSON files for everything. It worked, but was a nightmare of management. I switched over to SlqLite and everything was a lot more simpler. But SqlLite is just so annoying, "I can't use ALTER", very messy to change columns.

I have a older "Series" API that is like media, but worse. It was directly accessing folders on the device and showing files. This could have been a security nightmare, so I switch over to Media API instead.

The media API is basically converts media into GUID.dat files that are stored in the PRIMARY or ARCHIVED media folder. The idea here was to place content you want to watch on the FAST primary drive, and move content you already watched over to a slower and larger storage drive. I had a system to track where you were watching, but I haven't added it back yet.

I explicitly built in a button to restart and stop the server. Because it used a special version of curl, that can emulate chrome browsers I could not really test locally, so I always tested from my Raspberry PI 5. This is why my private source version of this has 460+ commits, making tiny changes, pushing them to github. The restart button was tied into a script that will exit the program and when it detects the value 69, it loop the batch file, download source from GitHub, and rebuild when necessary.

Source Code:

https://github.com/mgatelabs/LimitedMediaServer
https://github.com/mgatelabs/LimitedMediaServerSite

I got this to work on my RP5, the Server project has some of my setup stuff, but it's missing how to make an official service and generate the self signed certs.

You could run it on windows, but the book downloading stuff won't work, that's linux only because of CURL. Also the features to scrape specific websites have been removed. The code to do it is still there with a sample Processor.

0 Comments
2024/10/30
02:58 UTC

0

Hello! How can I upload a code that I made (A calculator for pollution) To a website? I made it with tkinter But I dont know how to put it online

The code is made with python and I'm using tkinter for the GUI but I have No clue how to upload it online.

2 Comments
2024/10/29
15:46 UTC

5

Lazy Web App for RPi

Like everything in IT, spend hours of time to automate the most simplest of tasks. Created an update/reboot web app for my raspberry pi without needing to get on my PC to SSH into it.

0 Comments
2024/10/28
23:17 UTC

0

Dash app : is there a way to store data input by the user ?

i want to make an app where the user types in data manually then these data is plotted (SPC chart, actual data point , avg, USL, LSL etc...) .

As for now i don't know how the Dash app would handle data input ? it looks like Dash provide input component but how would i link this with database for persistent storage ,, ?

Thanks

5 Comments
2024/10/28
14:28 UTC

4

How to setup a permanent session in default Flask?

If I use Flask-Session to store session data server-side, it is as easy as passing SESSION_PERMANENT = False (not default Flask, unique to Flask-Session) to the app.config, then set the desired expiration time with , PERMANENT_SESSION_LIFETIME = desired_exp_time which is default Flask config.

If I use default Flask to store session data client-side, I need to set PERMANENT_SESSION_LIFETIME = desired_exp_time first, then state session.permanent = True in the request (ex. u/app.route), else I get this error: RuntimeError: Working outside of request context. The docs is somewhat unclear about how to implement, see here.

What I don't understand is how to setup the default Flask one. I tried to google, and found this in Stack Overflow. The accepted answer suggests setting it with before_request, but I think why every request, we need to set session.permanent = True?

  1. How to set permanent sessions in default flask properly? Where to set it?
  2. Can you toggle permanent and non permanent session?
  3. What should we do after session is expired? What about the session data?
0 Comments
2024/10/28
05:25 UTC

5

Discord recommendations for Flask Devs?

What are the best Discords for Flask developers? Some general python discords are welcomed as well.

4 Comments
2024/10/27
17:26 UTC

2

Beginner in Web Dev – Need Advice on Architecting a Website for a RAG System Chatbot (Using Flask/Python)

I’m building a simple chatbot website to deploy a Retrieval-Augmented Generation (RAG) system I’ve developed, and I need some advice on the architecture. The generator itself runs through an API, and my goal is to keep the setup efficient and fast. I’m experienced in ML but new to web development, so I’d love some pointers on how to structure this in a way that’s simple and effective.

If anyone has experience building a website for a RAG system, I’d love to hear about your architecture—especially how you set up and deployed the API for handling requests. Did you use something specific to optimize for speed and resource management? Any tips for handling responses and managing requests would be super helpful, especially for Flask/Python setups. Thanks in advance!

2 Comments
2024/10/26
20:50 UTC

3

How do I compare a form in CKEditorField and StringField?

I am using flask and flask-sqlalchemy and flask-wtf-forms.

Imagine I have 2 forms where one form is placed in each flask route.

Lets start with the first route and the first form.

The 1st form has the flask wtf field CKEditorField. Within the route I type zzz in the form. Next I save this in the Posts table as the content column. Now lets switch to the second route and second form.

In the 2nd route I am using StringField. Then in a form, I input/type zzz. Now I am using a custom validator in the form and I query one_or_None for the Posts table. If Posts returns something I then test if posts_db.content == content_form' I raise the validationerror('the post is not unique"). This should work but what if I use something like bold in the ckeditor form. How would I get the output in the second Stringfield form? The only solution I can think of is passing on the variable posts_db in the route. Does anyone have any other suggestions?

TLDR:

I have 2 forms. The 1st form being CKEditorField ,in the 1st route, which I fill with the text 'zzz' then save it the Posts db table.

I take the 2nd form in the 2nd route which has StringField. I create a custom validator that checks if the content column is unique in the Posts table. The problem is this is in the StringField form. If I typed 'zzz' in the ckeditorfield form then query the Posts db table and compare it to the the StringField 'zzz' they are different if I use something like bold. How do I fix this?

My Solution

I also realize I could make both forms the same type but due to the way the code is setup I really want to keep the different types of forms. Though it doesn't have to be StringField it could be TextField. But the other form CKEditorField I really want it to be the same.

Another solution is to pass on a variable in the route and use one_or_none. But I don't think that will work.

Can anyone think of a better solution?

1 Comment
2024/10/26
20:48 UTC

10

Build a 'Chat with Wikipedia' App Using Flask and Gemini API (Demo + Code)

Hey Community,

I’m excited to share how quick and easy it is to bring your apps and ideas to life using Flask—the learning curve is really user-friendly! I recently built a "Chat with Wikipedia" app using Flask, powered by the Gemini API.

You can check out a demo on my YouTube channel (link provided in the video description), where you’ll also find the code.

Here’s a quick overview: this app lets you enter a Wikipedia page title and chat with the page to ask questions about it.

Next on my list is to develop a Chrome extension to extend this concept, making it possible to chat with any website directly.

Let me know what you think!

https://www.youtube.com/watch?v=1mxTvmpDV-I

0 Comments
2024/10/25
10:53 UTC

1

REST API Testing - Where to run functional tests?

Hello,

At work, I'm developing a REST API with flask, and I'm wondering where I should run my functional tests.

My current CI/CD pipeline on github actions runs the unit tests (mocking / patching ) for small blocks of code, and also runs the integration tests using a docker compose (spins up database instance, and some other services on the same machine, then runs tests)

Both those tests above run locally, and run during push and merges to github.

I also have functional testing for the REST API, using pytest with request library. Once the docker image is running in a test environment on AWS (EC2), I want to be able to make calls and check if the API is working properly

My question is where should these be run from and what do most professional organizations do? Should they run:

- Locally? (i.e. my local computer send the request to the live test server on AWS)

- On the Github action CI/CD pipeline? if so can i configure these to run after the docker image is running?

- On the EC2 instance itself (maybe in another container)

- Somewhere else?

Thanks for any advice!

2 Comments
2024/10/24
21:51 UTC

12

How do Session IDs work?

New to Flask. What I know is there are 2 ways to implement sessions: client-side and server-side. The former uses the default flask session (from flask import session) while the later uses a library called Flask-Session (need to add from flask_session import Session) .

I read both flask and Flask-Session docs, I still can't wrap my head around how sessions really work. The default session will turn your session data dict into cookie, then salt it, add signature, encode in base64. The Flask-Session's session still uses cookie, but it only contains the session identifier.

Session identifier is for identifying users, duh. But I have some questions:

  1. Since Flask-Session is just extension of the deault session, do both of them implement the same approach to assigning session ID?
  2. Where can I find the session IDs of the users?
  3. Is it going to reset after closing the tab? browser?
  4. When I do session.clear(), is everything cleared, including the session ID?

Again, sorry for asking these dumb questions. Any help would be appreciated. Thanks!

EDIT: Both session.permanent = False (default Flask) and SESSION_PERMANENT = False (Flask-Session) removes the session cookie when the browser is closed, not tab. It is somewhat unreliable. I tested it. Say, the user has another browser window open, the cookie will still be there. Docs

16 Comments
2024/10/24
16:19 UTC

9

Personal portfolio

Finally fixed my mobile menu! Really excited about how this is coming along... In the resources section I have a ecomm template but let me know if anyone want this portfolio template in that section so I can add it. More feedback welcome!
thanks in advanced Reddit people!
https://silverboi.me

3 Comments
2024/10/24
16:02 UTC

1

Flask SQLAlchemy/SQLlite dont accept datatime objs

Hello, guys. Firstly, sorry my bad english.

Well, I`m trying to commit a obj to a database, but SQLAlchemy/SQLite dont accept my datetime objs. The all data has the correct datetype, but for some rason, I cant commit. You see, my class request specifics data types and I provide. You can see which data I want to comit in the class, they match with the columns, but raises a error. Help, pls.

https://preview.redd.it/uskohz8vpowd1.png?width=982&format=png&auto=webp&s=22c2a67a2fe76c069ed4a6e5f4f1b0c559799423

https://preview.redd.it/zkisqw8vpowd1.png?width=404&format=png&auto=webp&s=34092961db7b226e1e8946b6cacfe7796137c69f

https://preview.redd.it/rw2d269vpowd1.png?width=519&format=png&auto=webp&s=85403f868adcc21fddcfffbe47428ac827b3d252

https://preview.redd.it/5a5j659vpowd1.png?width=732&format=png&auto=webp&s=5277246ea756029d104bd2cd3a0d714e7adf53c2

7 Comments
2024/10/24
10:53 UTC

2

Hosting my Flask application - selecting a provider?

I'm currently looking to host my Flask application that is completely finished and just needs to go online, but as it is my first project that is actually going online I'm looking for some guidance with selecting a provider.

The app is a statistics application that I built for a company. It's a fairly basic Flask application with upwards of 8 .py scripts, a .json dataset and and some web templates, images and .css files. Everything is running smoothly and perfectly on the built-in development server, so I'm hoping it will continue to do so once hosted properly.

Security is a concern (if that matters when it comes to selecting the provider) as the application uses developer keys and some other credentials (that I've done all I can to secure within the app itself). I will need to install a log-in system of some sort so if any provider can make that easy that would be a major advantage.

Hoping for some pointers or just to hear some experiences with different providers - and thanks in advance :-)

T

15 Comments
2024/10/24
08:48 UTC

Back To Top