/r/flask
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 [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
/r/flask
I have code query below. Anniversary stores the number of years after burial date. If anniversary is less than or equal to zero, then the deceased person is not yet buried, therefore, users are allowed to send condolence messages, otherwise the tab changes to anniversary messages. A user is only allowed to send one condolence or anniversary message, otherwise the button to edit his/her condolence/anniversary message appears. But unfortunately the author_dict is not getting populated for the code to check whether a user has already posted or not. Help me understand and correct my code why the authors_dict is not getting populated. The database has data. I am using flask, sqlachemy and sqlite database:
# Initialize the dictionary
authors_dict = {}
# Manually initialize the lists within the dictionary
authors_dict["authors_condolences"] = []
for i in range(1, anniversary + 1):
variable_name = f"authors_{i}{get_suffix(i)}"
authors_dict[variable_name] = []
# Populate the authors_dict
for condolence in condolences:
year_extracted = db.session.query(func.extract('year', condolence.dead.burial_cremation_date)).scalar()
print("Year extracted:", year_extracted)
print("Today year:", today_year)
# For condolences
if func.abs(year_extracted - today_year) == 0:
authors_dict["authors_condolences"].append(condolence.author)
# For anniversaries
elif func.abs(year_extracted - today_year) == anniversary:
variable_name = f"authors_{anniversary}{get_suffix(anniversary)}"
authors_dict[variable_name].append(condolence.author)
Hey guys feel free to roast my project.
🌐 link https://www.spliffpay.xyz
Test wallet adress:
0x95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5
I created this project for a college project, but I have doubts about how I should do the unit and integration tests. I created some tests, but my colleague said they were e2e tests, which does not fit the job requirements. So if anyone can explain how I should do these tests and how far my tests are from the objective of the work.
https://github.com/GabrieldbSouza/Personal-Finance-Management/tree/main/server%2Ftests
My goal is to generate a signature line with the persons name that’s generated in a dps.input. It ask them how many members they have -> creates inputs based on how many members - > then makes signature lines, but after I create the input fields I can’t find a way to get the information from the input field. I thought I’d be able to re-loop x to get the names {{ dps.data.x|string }} but that doesn’t work and using 0-4 isn’t either.
{{ dps.input("numberOfMembers", "Number of Members", required=True) }}
{% set memberNumber = [] %}
{% if dps.data.numberOfMembers %}
{% for x in range(dps.data.numberOfMembers|int) %}
{{ memberNumber.append(x|string) }}
{{ dps.input(memberNumber[loop.index0], "Member", required=True) }}
{% endfor %}
{% endif %}
{% if dps.data.numberOfMembers %}
{% for x in range(dps.data.numberOfMembers|int) %}
<table style="width: 100%; table-layout: fixed; "><tr><th colspan="1" style="padding-bottom: 1em; "></th><th colspan="1" style="padding-bottom: 1em; "></th><th colspan="1" style="padding-bottom: 1em; "></th></tr><tr><td style="width:33%; "><span class="check\_fillin" style="font-style:8.5pt; width:100%; line-height:6pt"></span>
</td><td style="width:33%; font-weight: bold; text-align: left; "></td><td style="width:33%; ">Dated:<span class="check\_fillin" style="font-style:8.5pt; width:80%; line-height:6pt"></span>
</td></tr><tr style="vertical-align: top;"><td style="width:25%; font-weight: bold; vertical-align: top; text-align: left;">{{ dps.data.x|string }}Member
</td><td style="width:25%; font-weight: bold; vertical-align: top; text-align: left;"></td><td style="width:40%; vertical-align: top; text-align: left;"></td></tr></table>{% endfor %}
{% endif %}
Are you tired of spending valuable time setting up the same boilerplate code every time you start a new Flask project? Say hello to Flask Boilerplate Generator - your ultimate time-saving tool for Flask development!
Flask Boilerplate Generator streamlines the development process by automating the setup of a Flask project with just a few simple commands. Whether you're a seasoned Flask developer or just starting out, this tool will help you get your project up and running in no time.
== Key Features ==
Effortless Setup: Simply install the package from Github and use the command-line interface to create a new Flask project with a predefined folder structure and blueprint setup.
Virtual Environment Management: Automatically sets up a virtual environment for your project, ensuring clean and isolated dependencies.
Blueprint Configuration: Quickly scaffold your project with pre-configured blueprints for common application components like authentication, administration, error handling, search, account settings, views, database(model) and more.
Security Enhancements: Includes built-in security measures such as CSRF protection, HTTP headers middleware, and secure session management to help keep your application safe from common vulnerabilities.
======== User Commands: To Get Started Quickly ======= Flask Boilerplate Generator provides convenient commands to streamline your project setup:
=======Create Project Folder:=======
Bash or Terminal
flask-manage create-app my_demo_app
(This command creates a new directory for your Flask application)
=======Create Virtual Environment:=======
Bash or Terminal
flask-manage -v
(The -v flag creates a virtual environment to isolate your project's dependencies.)
=======Create Both (Virtual Environment & App or Project):=======
Bash or Terminal
flask-manage -v create-app my_demo_app
==== Note ===== You can change my_demo_app to any name of your choice
==== Link to the github ==== https://github.com/Kennarttechl/flask_boilerplate_generator.git
Hello there,
I have only one working route
@app.route('/teams', methods = ['GET'])
def index():
"""
Endpoint to retrieve a list of all teams.
Retrieves all teams from the database, serializes them using the TeamSchema,
and returns the serialized data in JSON format.
Returns:
Response: Flask response object with JSON data containing all teams and a 200 HTTP status code.
"""
get_teams = Team.query.all()
team_schema = TeamSchema(many = True)
teams = team_schema.dump(get_teams)
return make_response(jsonify({"teams":teams}))
I tried to add POST method to this route, then I hit it with postman and I got 405 Method not allowed. From this point everything broke.
@app.route('/teams', methods = ['POST'])
def create_team():
data = request.get_json()
team_schema = TeamSchema()
try: team = team_schema.load(data) #add validation for handling unknown fields
except ValidationError as err:
return make_response(err.messages)
result = team_schema.dump(team.create())
return make_response(jsonify({"team": result}))
I tried to add different route
@app.route('/jozo', methods=['GET'])
def jozo():
return make_response("hello")
but it just says 404 url not found.
I tried to make new flask app to test and whatever I tried it always goes 404 URL not found. I don't understand how all routes but one (/teams with GET method) are broken. I tried to unistall flask and install it back with no result. I also tried to clear browser cache.
Thank you for any tips in advance!
Hi guys, I'm trying to query a child and return its parent as well (and vice-versa).
This is a sample of my models:
class Parent(db.Model):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
children = relationship(Child, passive_deletes=True, lazy=True, backref='parent')
class Child(db.Model):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id', ondelete='CASCADE'), unique=False, nullable=False)
Since the objects created from those models aren't json serializable, I'm calling to_dict()
function to make them a dictionary, but of course, this is going to cause an infinite recursion.
Is there another way to achieve this?
Do I just ask for help here? Pretty new to flask and trying to get a simple website for my assignment to just display the weather after grabbing it from weathermap org.
So i'm a complete begginer trying t buils a very simple web app to test what i've learned and my skills . And the problom is that i want to use flak to mange the backend . Should i use an other framework for the frontend ? if yes , it's Nextjs for me so how can connect these two and have my app finally ?
I'm new to flask and sql, and I'm trying to populate a database during the init-db command so that the data can be retrieved through a view. (I'm following the official tutorial on flask page)
I added a query like below in the init_db function.
def init_db():
db = get_db()
with current_app.open_resource('schema.sql') as f:
db.executescript(f.read().decode('utf8'))
query = """INSERT INTO rtc_timeseries_data VALUES (
?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
)"""
data = [(row[1], .... , row[33]) for row in rtc_data.itertuples()]
db.executemany(query, data)
And I am trying to retrieve it from a view like this:
u/app.route('/hello', methods=(['GET']))
def hello():
db = get_db()
result = db.execute(
'SELECT state FROM rtc_timeseries_data;'
).fetchone()
data = [{'state': result} for row in result]
return jsonify(data)
I'm getting the error below:
`TypeError: 'NoneType' object is not iterable`
So I'm trying to get an ssl certificate for my domain using https://letsencrypt.org/ on my linux machine. However, out of all the tutorials I have tried, not a single command relating to nginx or snapd has worked.
So I am wondering, is there any way to just tell certbot to generate a certificate for my flask server and thats it without having to boot up 20 thousand different things and 200 config files? Any help is appreciated, thanks.
I'm using flask as my server and ngrok to serve it.
Hi guys, I am currently doing a project, and I am stuck in linking my python backend with the HTML interface. and currently I am using Flask and ngrok as I want to make it available in website, but the things is everytime when I want to access it on another pc (in the same local network), it cannot be worked, even in my pc, when i need to access it, i need to close the agent and open it again, Can i know what's wrong with it and how can I solve it?Is using flask the correct way to do or any other better way to link my interface with python? This is the way I link my html interface with my script.
from flask import Flask, render_template, request
from flask_ngrok import run_with_ngrok
app = Flask(__name__)
run_with_ngrok(app)
app.template_folder = 'templates'
@app.route('/')
def index():
return render_template('UIChat.html')
import time
@app.route('/submit', methods=['POST'])
def submit():
begin = time.time()
print(begin)
chat_history = []
# Get user input from the form
query = request.form.get('message')
# Process the input in your Python script (e.g., call your QA function)
result = chain({'question': query, 'chat_history': chat_history})
output = result['answer']
end = time.time()
print(f"Total runtime of the program is {end - begin}")
chat_history.append((query,output))
return render_template('UIChat.html', user_input=query, bot_response=output)
# Return the response in the bot-response div
app.run()
Hello, I'm planning on making an web application with plug-in support (where a user can make it's own plug-in) using Flask, but I don't have any idea on how to do it or where to start. I need suggestions on tools and learning material. Any help/tips are appreciated, thanks.
I have created a social network with Flask and everyone can try it, The social network is made with Flask and MySQL, and is deployed in EC2, and if you want to try it here is a screenshot and link: https://www.socialspace.cloud/
At my current internship, I've finished the basics of my service. Right now for testing, its set up as a flask application and is being tested with postman.
I've setup a connection to the company's database through SQLAlchemy which modifies a dynamic stored procedure in order to fetch the specific data. The same procedure processes the data which is then sent through a Prophet model to plot and predict a sickness curve. The datapoints are extracted and saved in a cache local SQLAlchemy database for 24h.
The plan is, once every night, this procedure iterates through each of the combination of parameters (around 160) and saves the data points in the caching db. Then when the user makes a request the answer comes almost instantly.
What is the best way for deployment here? Everything I can find online is just "Hello world" app deployments.
I made a flask app that’s kinda slow because it does complex database operations. It is what it is. The data doesn’t change all that much, daily fidelity is plenty.
Could I cache return render template somehow as static html for each of the slow routes? Would be much faster to read the data from disk thank dynamically query it
What I am thinking is to maybe have a cronjob to write static html files using a background flask worker and then return literally just the muliline string as response? Hacky approach but should work, no?
Maybe there’s a better way?
Hi all, I am creating an application where my application will send a webhook callback URL to 3rd party website on internet when will then send data to this URL when any event happens.
Few questions I have on my mind is,
Is there CORS list in flask by default which i would have to overwrite to receive data from 3rd party wensite.
How will I send the call back URL to the website i mean in production i could maybe just use url_for("webhookCallback", external=True)
but not sure how will I send url in development. For testing
If you have worked with webhook in flask please let me know, I could look at your project.
Please tell your thoughts on this.
I want to hear some thoughts on it since I am having trouble finding a free hosting server for a flask application that can deal with h5 files (model files).
import json
from flask import Flask, request, jsonify
from flask_cors import CORS
from app.models.user import User
from app.models.engine.db_storage import DBStorage
app = Flask(__name__)
CORS(app)
db_storage = DBStorage(app)
u/app.route('/')
def home():
return "Hello, Flask!"
u/app.route('/student', methods=['GET','POST'])
def register():
try:
data = request.json
user = User(
first_name=data.get('first_name'),
last_name=data.get('last_name'),
email=data.get('email'),
reg_no=data.get('reg_no'),
role=data.get('role'),
password=data.get('password')
)
print(user)
db_storage.new(user)
db_storage.save()
response = {'message': 'Registration successful'}
return jsonify(response), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
finally:
db_storage.close()
if __name__ == '__main__':
app.run(debug=True)
I am trying to add data to my database this my code in the main.py:
#!/usr/bin/python3
"""
New class for sqlalchemy
"""
from os import getenv
from flask import jsonify
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy import (create_engine)
from app.models.base_model import Base, BaseModel
from app.models.user import User
class DBStorage:
"""Create table in environmental"""
__engine = None
__session = None
def __init__(self, app=None):
if app:
"""
user = getenv("FGP_MYSQL_USER")
passwd = getenv("FGP_MYSQL_PWD")
db = getenv("FGP_MYSQL_DB")
host = getenv("FGP_MYSQL_HOST")
"""
user = "root"
passwd = "root"
db = "faceguardpro_db"
host = "localhost"
self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'
.format(user, passwd, host, db),
pool_pre_ping=True)
self.reload()
def all(self, cls=None):
"""
:param cls:
:return: Return a dictionary of __object
"""
dic = {}
if cls:
if type(cls) is str:
cls = eval(cls)
query = self.__session.query(cls)
for elem in query:
key = "{}.{}".format(type(elem).__name__, elem.id)
dic[key] = elem
else:
list = [BaseModel, User]
for cls in list:
query = self.__session.query(cls)
for elem in query:
key = "{}.{}".format(type(elem).__name__, elem.id)
dic[key] = elem
return (dic)
def new(self, obj):
"""
Adds a new object to the database.
:param obj:
:return:
"""
self.__session.add(obj)
print("A new user has been created")
def save(self):
"""
Commits changes to the database.
:return:
"""
self.__session.commit()
print("A new user has been saved")
def delete(self, obj=None):
"""
Deletes an object from the database.
:param obj:
:return:
"""
if obj:
self.__session.delete(obj)
def reload(self):
"""
Creates all tables and sets up a new session
for interacting with the database.
:return:
"""
Base.metadata.create_all(self.__engine)
session = scoped_session(sessionmaker(bind=self.__engine, expire_on_commit=False))
self.__session = session()
def close(self):
"""
Closes the session.
:return:
"""
self.__session.close()
print("The session is closed")
And this is my db_storage.py file
When I try to post data, it is not being committed. Everything is working correctly and I get the message A new user has been created and then I get the session is close, so I was able to determine that the commit() session is not working, what could be the issue? Any help will be appreciated
error = "Internal Server Error, The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application."
Is there any blog or tutorial of such integration? I have a very structured blueprints that's kind of separate from each other. Alot of the guides and official documentation have been using just a simple app.py inside the project folder to run the flask app instead of using factory pattern as suggested.
Indeed if I place an app.py and do python app.py to start and route to a index.html as landing it, the tailwindcss will show up. But the moment I change to use factory pattern to start the app it will not show up? Why is that so, is there anyone who managed to do it and could share your repo or how u structure ur application?
And also if we build with npx tailwind, do we have to write script one by one to build into our blueprints static folder ?
Since Flask ha depreciated before_first_request method since Flask2.2, what are the alternatives?
Currently my app loads model after the first request is hit. because it runs on \@before_first_request decorator in Flask 2.2.
What are the ways to load model on server or app starts
var socket = io.connect('http://127.0.0.1:5000');
socket.on("connect", function() {
socketID = socket.id;
console.log("Socket ID: ", socketID);
})
var statusElement = document.getElementById('processingStatus');
// Listen for 'update' events from the server to get real-time processing updates
socket.on('update', function(data) {
console.log('Update from server:', data.message);
statusElement.innerHTML = data.message; // Update UI
if (data.message) {
progressWindow = document.getElementById('success-overlay')
progressWindow.style.display = 'block';
}
// Check if the received message is 'Processing completed'
if (data.message === 'Processing completed') {
statusElement.innerHTML = 'Processing completed, getting info';
setTimeout(function() {
window.location.href = `/pdf-display?file=${encodeURIComponent(chosenFile)}`;
}, 3000); // Redirect to display page after 3 seconds
}
});
// Set up XMLHttpRequest to send the filename to the server
var request = new XMLHttpRequest();
request.open('POST', 'http://127.0.0.1:5000/generateTextContent', true);
request.setRequestHeader('Content-Type', 'application/json');
request.onload = function() {
// Handle response from server
if (!(request.status >= 200 && request.status < 400)) {
console.log('Server returned an error:', request.status);
}
};
request.onerror = function() {
console.log('Request failed to reach the server');
};
// Send the filename as JSON
request.send(JSON.stringify({ filename: chosenFile, socketID: socketID }));
from flask import *
from config import socketio
import os
from werkzeug.utils import secure_filename
from werkzeug.security import safe_join
from flask_cors import CORS
from dotenv import load_dotenv
# Chat imports
import openai
import fitz # PyMuPDF
app = Flask(__name__)
CORS(app)
socketio.init_app(app, cors_allowed_origins="http://127.0.0.1:5000")
@app.route("/generateTextContent", methods = ['POST'])
def generate_text_content():
data = request.json
filename = data.get('filename')
socketID = data.get('socketID')
file_path = os.path.join(app.config['UPLOAD_FOLDER'], 'text_based/'+filename)
if os.path.exists(file_path):
from backend.Document_Controller import main as processDoc
print("Sending path to process: "+file_path)
socketio.emit('update', {'message': f'Starting processing for {filename}'}, to=socketID)
processDoc(file_path)
# Simulate processing completion
socketio.emit('update', {'message': 'Processing completed'})
return jsonify({'message': 'Processing initiated'}), 200
else:
return jsonify({'error': '('+file_path+') File not found'}), 404
if __name__ == '__main__':
socketio.run(app, debug=True)
[Edit] Got it to work by overriding the static folder on initiation. Apparently Flask has a strong expectation that /static/ sits within the same folder structure as your calling function unless you explicitly override (python - How can I override the static file handler in Flask? - Stack Overflow). Initiating with Flask(static_folder=None) solved the problem.
I'm using the following code for basic routing (just a proof of concept at this stage), and I'm able to get index.html to route correctly in my app.py, but for the static assets requested from index.html, the function serve_static() is not showing print statements, which means it is not being called. I am stuck and can't figure out why.
Would appreciate any help!
The URLs and filenames all seem accurate, and the server is registering the GET request, so it seems to be a problem in app.py where it is not routing properly, I think? In the html file:
<script defer="defer" src="/static/js/main.d66f505a.js"></script><link href="/static/css/main.f855e6bc.css" rel="stylesheet">
So this matches both to the files in my folder structure as well as the GET requests sent to server. But why isn't serve_static() being called?
from flask import Flask, send_from_directory
import os
app = Flask(__name__)
# Define route to serve the index.html file
u/app.route('/')
def index():
# Serve the index.html file from the auto/build directory
auto_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'auto')
index_file_path = os.path.join(auto_path, 'build', 'index.html')
print(index_file_path)
return send_from_directory(os.path.join(auto_path, 'build'), 'index.html')
# Define route to serve static files (js, css, etc.)
u/app.route("/static/<path:path>")
def serve_static(path):
print('1')
autobrd_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'auto')
print(os.path.join(auto_path, 'build', 'static'), path)
return send_from_directory(os.path.join(auto_path, 'build', 'static'), path)
# Define other routes and APIs as needed
if __name__ == '__main__':
app.run(debug=True)
127.0.0.1 - - [06/May/2024 16:06:05] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [06/May/2024 16:06:05] "GET /static/js/main.d66f505a.js HTTP/1.1" 404 -
127.0.0.1 - - [06/May/2024 16:06:05] "GET /static/css/main.f855e6bc.css HTTP/1.1" 404 -
127.0.0.1 - - [06/May/2024 16:06:06] "GET /manifest.json HTTP/1.1" 404 -
127.0.0.1 - - [06/May/2024 16:06:06] "GET /cart.json HTTP/1.1" 404 -
Hey everyone, so I'm trying to add a way that buyers and sellers can chat on my e-commerce project. It's a school project and I'm fairly new to coding. I have tried socketio and I'm not sure whether I'm doing it right but I'd appreciate anyone who can walk me through adding real time chatting functionality. I'm using react for my frontend btw. Thanks
Currently, I am building a web app using Python, Flask, HTML, CSS, and also integrating Firebase. I am very new to Firebase, so I am not able to figure out how to write the code to add 'Sign in with Google' functionality using Firebase. I already have a login route which logs in users using an email ID and password, so the 'Sign in with Google' feature would be an additional route. Please provide efficient code for my problem. It would be a great help for me.
Also, please note that the 'Sign in with Google' feature should work correctly. By this, I mean that after clearing the browser cache, the logged-in user should persist.
I have tried asking ChatGPT and Gemini and also have watched some videos but there are some errors : like some import error or other and after continuous fixing i was not able to fix the code.