python – Como usar a sessão (cookie) de outro site que não foi setado pelo flask

Gostaria de saber se existe uma maneira de usar um cookie setado por outro site, na minha aplicação no flask com python.

Preciso autenticar em um site que necessita o token tipo A3, porém, não consigo capturar esse token via cookie por necessitar de um validador do backend do site e nem tentar um parse de algum tipo para tentar autenticar manual.

O que eu imaginei para tentar fazer é um site em flask, que usa a sessão já existente utilizando o cookie que já está armazenado no navegador. É possível fazer algo assim?

from flask import Flask, redirect, request, session, render_template

def cookies():
    return request.cookies

Estou usando algo parecido com isso para verificar se o cookie foi setado, mas confesso que estou bem perdido se isso é possível ou não.

Agradeço pela ajuda.

python – Flask redirect not working after post request with apache

I started learning python and flask recently and I’m trying to deploy my site today. I used this tutorial: orials/how-to-deploy-a-flask-application-on-an-ubuntu-vps. Everything worked, but when I try to log in or register, the server can’t render the site that I want it to render. This is how it works when I run the server on my computer: And this is on my ubuntu vps:

This is my file which handles login, logout and registration:

@auth.route('/login', methods=('GET', 'POST'))
def login():
if request.method == 'POST':
    email = request.form.get('email')
    password = request.form.get('password')

    db = connect_database()
    cur = db.cursor(dictionary=True)
    sql = "SELECT * FROM users WHERE email = %s"
    val = (email, )
    cur.execute(sql, val)
    user = cur.fetchone()
    if not user:
        flash('K tomuto emailu neexistuje žádný účet!', category='error')
        return redirect(url_for('views.home'))
    if check_password_hash(user('heslo'), password):
        flash('Jsi přihlášen/a!', category='success')
        session('loggedin') = True;
        session('id') = user('userId')
        session('email') = user('email')
        return redirect(url_for('views.home'))
        flash('Špatný email nebo heslo. Zkus to znovu.', category='error')

return render_template("login.html")

def logout():
if 'loggedin' in session:
    session.pop('loggedin', None)
    session.pop('id', None)
    session.pop('email', None)
return redirect(url_for('auth.login'))

@auth.route('/sign-up', methods=('GET', 'POST'))
def signup():
if request.method == 'POST':
    email = request.form.get('email')
    first_name = request.form.get('firstName')
    password1 = request.form.get('password1')
    password2 = request.form.get('password2')
    db = connect_database()
    cur = db.cursor(dictionary=True)
    sql = "SELECT * FROM users WHERE email = %s"
    val = (email,)
    cur.execute(sql, val)
    user = cur.fetchone() 
    if user:
        flash('Email již existuje!', category='error')
    elif not re.match(r'^(a-z0-9)+(._)?(a-z0-9)+(@)w+(.)w{2,3}$', email):
        flash('Nevalidní email!', category='error')
    elif len(first_name) < 2:
        flash('Jméno musí mít alespoň 2 znaky!', category='error')
    elif password1 != password2:
        flash('Hesla se neshodují!', category='error')
    elif len(password1) <= 5:
        flash('Heslo musí mít alespoň 5 znaků.', category='error')
        password = generate_password_hash(password1, method='sha256')
        sql = "INSERT INTO users (jmeno, email, heslo) VALUES (%s, %s, %s)"
        val = (first_name, email, password, )
        cur.execute(sql, val)
        flash('Účet byl úspěšně vytvořen!', category='success')
        sql = "SELECT * FROM users WHERE email = %s"
        val = (email, )
        cur.execute(sql, val)
        user = cur.fetchone()
        session('loggedin') = True
        session('id') = user('userId')
        session('email') = user('email')
        return redirect(url_for('views.home'))

return render_template("sign_up.html", user=current_user)

And this is my .wsgi error log:

And tried searching for any solutions but couldn’t find any. Thanks to everyone for any help.

javascript – Mandar JSON de cliente a servidor FLASK

mi pregunta es sencilla. ¿Cómo puedo generar un JSON y mandarlo al servidor para su posterior tratamiento? La única forma que tengo es recoger la información de los formularios HTML mediante un request.form(x), pero supongo que habrá alguna forma de generar un JSON. Dejo a continuación el código:


@app.route('/homepage', methods=('GET','POST'))
def login():
    #Compruebo el método
    if request.method == 'GET': 
        name = request.json('name')
        user = mongo.db.users.find_one({'name': name})
        response = json_util.dumps(user)
        return response


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <form class="" action="{{ url_for('homepage') }}" method="GET">
        <h1 class="h3 mb-3 font-weight-normal">Sign in</h1>
        <input type=text id="name" placeholder="Name">
        <button class="btn btn-lg btn-primary btn-block">Sign in</button>

Como se ve, mi intención es recoger la información mediante request.json(x), pero no conozco la forma de generar este JSON.

Gracias de antemano.

mongodb – pymongo + flask + gunicorn: “Authentication failed” before first operation when “connect=False”

I’m using MongoDB Atlas. I’m have this URL for connecting: mongodb+srv://<LOGIN>:<PASSWORD>@<URL>/<DB>?retryWrites=true&w=majority&authSource=admin.

I’m using this stack: flask, gunicorn, pymongo, mongoengine (i don’t think that it is related, because mongoengine actually uses pymongo).

gunicorn config:

  • sync workers,
  • threads = 1,
  • workers count = 8

When connecting, i’m using connect=False because pymongo itself is not fork-safe. With connect=False it will connect to the DB before first operation. It need to be set to False, because gunicorn uses pre-fork model.

But I am faced with the following situation:

  1. On first request (endpoint makes some DB operations) i’m getting this error: pymongo.errors.OperationFailure: Authentication failed., full error: {'ok': 0, 'errmsg': 'Authentication failed.', 'code': 8000, 'codeName': 'AtlasError'}
  2. On second request everything is fine (i.e., DB operations were successfully completed).
  3. If you press many times on F5, then sometimes you will occur a “Authentication failed” error, and sometimes everything will be fine.

If i’m set connect=True, everything will be fine. I’m never seen this “Authentication failed” error.

But then i’m getting this warning message: UserWarning: MongoClient opened before fork. Create MongoClient only after forking. See PyMongo's documentation for details:

So, obviously, connect need to be set to False.

I’m tested with two workers. Looks like this situation occurs:

  1. Let’s say i have two gunicorn sync workers with following pid’s: 22429 and 22430.
  2. I’m getting request. Worker 22429 handles it. Everything is fine, because it is first worker and looks like it successfully made a DB connection.
  3. I’m pressing F5, worker 22429 again handles it and everything is fine.
  4. I’m pressing F5 again, and now worker 22430 handles it. It throws an error “Authentication failed.”
  5. I’m pressing F5 again, worker 22430 handles it. Now everything is fine, because that worker has made a connection.
  6. Now, all my workers (i have only two) were connected to the DB. Doesn’t matter how many times i’m press on F5, every request will be successfully completed.

But why it happens on first reques? From pymongo: “if connect=False, then connect on the first operation.”. If i’m understanding it right, pymongo should connect before actual first operation, successfully completed the connection, and only then perform that operation.

Then why my first DB operation fails for each worker? How i should handle this?

html – Jquery .text sometimes doesnt work with flask?

I have a small jquery script that should modifiy text passing through flask.
I use ajax to do so.

<i class="fas fa-heart likesspot" name = "{{spot.titre}}" style="color:#e86c60" ></i> <span id = "{{spot.titre}}_l">{{spot.likes}}</span>

         var name = $(this).attr("name");

         var fct = '/addlikesspot/'+name;
         $.ajax({  type: 'POST',  url: fct,
         success: function(data) {
                 $("#"+name+"_l").html("<b>"+data.matching_results(1).toString()+"</b>" );

note that each time I click the console log returns
with the good values

note also that the span is in a carroussel and it seems that the first carousel page always works whereas other page works randomly

python – What’s the best way to build a Flask API to control and show the status of a program tool I have built?

I’ve developed a backend project using Python. It collects data from different sources, process the data, and then perform actions with it (for example, store relevant info in a database). To execute it, I just do python and it starts the daemon process.

Now I want to add a Flask API in order to interact with this collector: start/stop the collection, see the state of each component, add/remove components… What is the best approach to do it? I can’t just add Flask app object and routes to the same project, because when I deploy the Api using Gunicorn with several workers, it runs several instances of the collector.

For example: I have in the collector a object called GlobalManager that is in charge of creating, deleting, starting and stoping the collector’s components. Obviously, there is only one instance of this GlobalManager, so I can’t include it in a project with Flask, because if I run it with Gunicorn, it starts several instances of the GlobalManager.

Should I code the API in a separate project and the communicate both the API and the collector through some tool?

How to deploy Flask application with Nginx and uWSGI?

I am deploying Flask application with Nginx and uWSGI for first time. Nginx will listen to port 8000 and WSGI will listen to 8081. I followed the instructions given in problem statement, but the NGINX fails to start.

Problem statement: Deploy a simple flask application with nginx and uwsgi.

Commands for configuring nginx server as per Problem statement:

  1. sudo vi /etc/nginx/nginx.conf
  2. The I was asked to include /projects/challenge/deploy.config in Virtual Host configs.
  3. sudo service nginx restart

For the code, this is what I did:

# Put your code here
from projects.challenge import app
if __name__ == "__main__":


server {
    listen 8000;
    server_name localhost:8081;

    location / {
        include uwsgi_params;

    location /Hello {
        alias /project/challenges/

The test code given in the question for testing deploy.conf is:

def test_conf_file_contents(self):
        with open('deploy.conf', 'r') as f:
            content =
            assert "location /Hello" in content
            assert "server localhost:8081" in content
            assert "listen 8000" in content

from flask import Flask, request, make_response

app = Flask(__name__)
app.secret_key = "Thisisyoursecret"

# Create a simple endpoint /Hello with return message "Welcome to your flask application"

def hello():
  res=make_response("Welcome to your flask application")
  return res

As per instruction in the question, I included deploy.conf in Virtual Host Configs of nginx.conf file as follows:

        # Virtual Host Configs

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
        include /projects/challenge/deploy.conf



The error is:

user@workspacede6jnv452qg2cr45:/projects/challenge$ sudo service nginx restart
 * Restarting nginx nginx                                                                (fail) 

On going to path etc/nginx and starting:

user@workspacede6jnv452qg2cr45:/etc/nginx$ sudo service nginx restart
 * Restarting nginx nginx

nginx is failing to restart when I include deploy.conf in Virtual configuration of nginx.conf. But it starts when I do not include deploy.conf.

I might be making some obvious mistake, I went through Google and Youtube but could not figure out what to fix. No solution worked. I suspect the deploy.conf file but I have no clue how to fix the issue.

Kindly suggest me what to do.

sql server – Flask – SQLAlchemy – Como retornar uma query para o mesmo template que a chamou

Bom dia pessoal.. Estou com o seguinte problema: Tenho o seguinte teplate roteiro.html

<form action="/consultaman" method="get">
    <input type="text" class="form-control" id="manifesto-input" name="pedcli" placeholder="Digite um manifesto">
    <input type="submit" id="manifesto-btn" value="Consultar">

e as seguintes rotas:

@app.route('/roteiro/', methods=('GET', 'POST'))
def roteiro(): 
   return render_template('roteiro.html')

@app.route('/consultaman/', methods=('GET', 'POST'))
def consultaman(man): 
   if request.method == 'GET': 
       search = "%{}%".format(man) 
       pedcli = Dt6010.query.filter( 
       return render_template('roteiro.html', pedcli=pedcli) 
return render_template('roteiro.html')**

Eu digito um manifesto no roteiro.html e filtro todos no BD. quero trazer de volta para o roteiro.html e pelo jinja fazer um { for } no pedcli para mostrar os dados. Ou seja, no próprio html eu digito a pesquisa e mostro os dados da pesquisa. Parece muito obvio mas é o meu primeito sistea WEB e estou ainda meio perdido. Se alguém puder me ajudar da o erro 404 .. agradeço

python – How do I fix a Not Found error in flask run?

I made a web app but whenever I run flask run I would get a 404 error.
This is the error I get in the terminal:

sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 140007095654144 and this is thread id 140007197614208.

and this is what I’ve got in

from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session, url_for
from flask_session import Session
from passlib.apps import custom_app_context as pwd_context
from tempfile import mkdtemp
from datetime import datetime
from import check_password_hash, generate_password_hash
import re
from helpers import *

app = Flask(__name__)

app.config("SESSION_FILE_DIR") = mkdtemp()
app.config("SESSION_PERMANENT") = False
app.config("SESSION_TYPE") = "filesystem"
app.config("PREFERRED_URL_SCHEME") = 'https'
app.config("DEBUG") = True

db = SQL("sqlite:///table.db")

@app.route("/login", methods=("GET", "POST"))
def login():
    """Log user in."""

    # forget any user_id

    # if user reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # ensure username was submitted
        if not request.form.get("username"):
            return apology("must provide username")

        # ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password")

        # query database for username
        rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))

        # ensure username exists and password is correct
        if len(rows) != 1 or not pwd_context.verify(request.form.get("password"), rows(0)("hash")):
            return apology("invalid username and/or password")

        # remember which user has logged in
        session("user_id") = rows(0)("id")

        # redirect user to home page
        return redirect(url_for("homepagee"))

    # else if user reached route via GET (as by clicking a link or via redirect)
        return render_template("login.html")    

@app.route("/login", methods=("GET", "POST"))
def register():
    if request.method == "POST":
        username = request.form.get("confirmation")
        password = request.form.get("password")
        confirmation = request.form.get("confirmation")

        if not request.form.get("username"):
            return apology("must provide username")

        # ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password")
        elif not request.form.get("confirmation"):
            return apology("must provide confirmation")
        elif request.form.get("password") != request.form.get("confirmation"):
            return apology("passwords must match")
        db.execute("INSERT INTO users(password, username) VALUES (password=:password, username=:username) WHERE id=:user_id", password=generate_password_hash(request.form.get("password")), username=request.form.get("username"), user_id=session("user_id"))  
        return render_template("homepagee.html")  
        return render_template("register.html")

def logout():
    """Log user out."""

    # forget any user_id

    # redirect user to login form
    return redirect(url_for("login"))

Can someone explain what the error means? Also, I don’t know if this will help or not, but I’ve copy pasted the main structure (everything except for the actual functions) from another file I’ve got and everything worked fine there.

apache2 – Configure Apache to associate subdirectory/subdomain to Flask port

I am running Flask on a server that has Apache installed. Users are accustomed to accessing websites on the server using subdirectories such as

My question is, can I make Apache show when is accessed whilst showing in the address bar? Up to now I have managed to create a redirection using an .htaccess file in but the address bar changes to which I would like to avoid.

I would be happy to use subdomains instead of subdirectories if it makes a difference (