flask | The Python micro framework for building web applications | Web Framework library

 by   pallets Python Version: 2.2.3 License: BSD-3-Clause

kandi X-RAY | flask Summary

flask is a Python library typically used in Server, Web Framework, Framework applications. flask has no bugs, it has no vulnerabilities, it has a Permissive License and it has high support. However flask build file is not available. You can install using 'pip install flask' or download it from GitHub, PyPI.
The Python micro framework for building web applications.
    Support
      Quality
        Security
          License
            Reuse
            Support
              Quality
                Security
                  License
                    Reuse

                      kandi-support Support

                        summary
                        flask has a highly active ecosystem.
                        summary
                        It has 62277 star(s) with 15507 fork(s). There are 2141 watchers for this library.
                        summary
                        There were 1 major release(s) in the last 6 months.
                        summary
                        There are 3 open issues and 2466 have been closed. On average issues are closed in 16 days. There are 2 open pull requests and 0 closed requests.
                        summary
                        It has a negative sentiment in the developer community.
                        summary
                        The latest version of flask is 2.2.3
                        flask Support
                          Best in #Web Framework
                            Average in #Web Framework
                            flask Support
                              Best in #Web Framework
                                Average in #Web Framework

                                  kandi-Quality Quality

                                    summary
                                    flask has 0 bugs and 0 code smells.
                                    flask Quality
                                      Best in #Web Framework
                                        Average in #Web Framework
                                        flask Quality
                                          Best in #Web Framework
                                            Average in #Web Framework

                                              kandi-Security Security

                                                summary
                                                flask has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
                                                summary
                                                flask code analysis shows 0 unresolved vulnerabilities.
                                                summary
                                                There are 0 security hotspots that need review.
                                                flask Security
                                                  Best in #Web Framework
                                                    Average in #Web Framework
                                                    flask Security
                                                      Best in #Web Framework
                                                        Average in #Web Framework

                                                          kandi-License License

                                                            summary
                                                            flask is licensed under the BSD-3-Clause License. This license is Permissive.
                                                            summary
                                                            Permissive licenses have the least restrictions, and you can use them in most projects.
                                                            flask License
                                                              Best in #Web Framework
                                                                Average in #Web Framework
                                                                flask License
                                                                  Best in #Web Framework
                                                                    Average in #Web Framework

                                                                      kandi-Reuse Reuse

                                                                        summary
                                                                        flask releases are available to install and integrate.
                                                                        summary
                                                                        Deployable package is available in PyPI.
                                                                        summary
                                                                        flask has no build file. You will be need to create the build yourself to build the component from source.
                                                                        summary
                                                                        flask saves you 4755 person hours of effort in developing the same functionality from scratch.
                                                                        summary
                                                                        It has 10184 lines of code, 1378 functions and 96 files.
                                                                        summary
                                                                        It has medium code complexity. Code complexity directly impacts maintainability of the code.
                                                                        flask Reuse
                                                                          Best in #Web Framework
                                                                            Average in #Web Framework
                                                                            flask Reuse
                                                                              Best in #Web Framework
                                                                                Average in #Web Framework
                                                                                  Top functions reviewed by kandi - BETA
                                                                                  kandi has reviewed flask and discovered the below as its top functions. This is intended to give you an instant insight into flask implemented functionality, and help decide if they suit your requirements.
                                                                                  • Generate a URL for an endpoint
                                                                                    • Inject url defaults
                                                                                    • Handles URL build errors
                                                                                    • Create a URL adapter
                                                                                  • Add a url rule
                                                                                    • Defines a GET rule
                                                                                    • Creates a route for a method
                                                                                  • Register this blueprint
                                                                                    • Creates a blueprint setup state
                                                                                  • Serialize obj to fp
                                                                                  • Copy the current request context
                                                                                  • Handle registration
                                                                                  • Return a logger instance
                                                                                  • Handle login
                                                                                  • Create a new blog
                                                                                  • Add a before_first_request function to the blueprint
                                                                                  • Callback to load an env file
                                                                                  • Deprecated
                                                                                  • Returns a response object
                                                                                  • Create a config object
                                                                                  • Run command
                                                                                  • Create a JSON response
                                                                                  • Create a route callable
                                                                                  • Saves a session
                                                                                  • Create a flask app
                                                                                  • Run shell
                                                                                  Get all kandi verified functions for this library.
                                                                                  Get all kandi verified functions for this library.

                                                                                  flask Key Features

                                                                                  The Python micro framework for building web applications.

                                                                                  flask Examples and Code Snippets

                                                                                  Including WSGI - Flask, Django, others-Check it
                                                                                  Pythondot imgLines of Code : 4dot imgLicense : Permissive (MIT)
                                                                                  copy iconCopy
                                                                                  
                                                                                                                      Hello, World from Flask!
                                                                                  { "message": "Hello World" }
                                                                                  包含 WSGI - Flask,Django,其它-检查
                                                                                  Pythondot imgLines of Code : 4dot imgLicense : Permissive (MIT)
                                                                                  copy iconCopy
                                                                                  
                                                                                                                      Hello, World from Flask!
                                                                                  { "message": "Hello World" }
                                                                                  Including WSGI - Flask, Django, others-Using WSGIMiddleware
                                                                                  Pythondot imgLines of Code : 1dot imgLicense : Permissive (MIT)
                                                                                  copy iconCopy
                                                                                  
                                                                                                                      {!../../../docs_src/wsgi/tutorial001.py!}
                                                                                  flask - auth
                                                                                  Pythondot imgLines of Code : 75dot imgLicense : Non-SPDX (BSD 3-Clause "New" or "Revised" License)
                                                                                  copy iconCopy
                                                                                  
                                                                                                                      import functools from flask import Blueprint from flask import flash from flask import g from flask import redirect from flask import render_template from flask import request from flask import session from flask import url_for from werkzeug.security import check_password_hash from werkzeug.security import generate_password_hash from flaskr.db import get_db bp = Blueprint("auth", __name__, url_prefix="/auth") def login_required(view): """View decorator that redirects anonymous users to the login page.""" @functools.wraps(view) def wrapped_view(**kwargs): if g.user is None: return redirect(url_for("auth.login")) return view(**kwargs) return wrapped_view @bp.before_app_request def load_logged_in_user(): """If a user id is stored in the session, load the user object from the database into ``g.user``.""" user_id = session.get("user_id") if user_id is None: g.user = None else: g.user = ( get_db().execute("SELECT * FROM user WHERE id = ?", (user_id,)).fetchone() ) @bp.route("/register", methods=("GET", "POST")) def register(): """Register a new user. Validates that the username is not already taken. Hashes the password for security. """ if request.method == "POST": username = request.form["username"] password = request.form["password"] db = get_db() error = None if not username: error = "Username is required." elif not password: error = "Password is required." if error is None: try: db.execute( "INSERT INTO user (username, password) VALUES (?, ?)", (username, generate_password_hash(password)), ) db.commit() except db.IntegrityError: # The username was already taken, which caused the # commit to fail. Show a validation error. error = f"User {username} is already registered." else: # Success, go to the login page. return redirect(url_for("auth.login")) flash(error) return render_template("auth/register.html") @bp.route("/login", methods=("GET", "POST")) def login(): """Log in a registered user by adding the user id to the session.""" if request.method == "POST": username = request.form["username"] password = request.form["password"] db = get_db() error = None user = db.execute( "SELECT * FROM user WHERE username = ?", (username,) ).fetchone() if user is None: error = "Incorrect username." elif not check_password_hash(user["password"], password): error = "Incorrect password." if error is None: # store the user id in a new session and return to the index session.clear() session["user_id"] = user["id"] return redirect(url_for("index")) flash(error) return render_template("auth/login.html") @bp.route("/logout") def logout(): """Clear the current session, including the stored user id.""" session.clear() return redirect(url_for("index"))
                                                                                  flask - test blog
                                                                                  Pythondot imgLines of Code : 58dot imgLicense : Non-SPDX (BSD 3-Clause "New" or "Revised" License)
                                                                                  copy iconCopy
                                                                                  
                                                                                                                      import pytest from flaskr.db import get_db def test_index(client, auth): response = client.get("/") assert b"Log In" in response.data assert b"Register" in response.data auth.login() response = client.get("/") assert b"test title" in response.data assert b"by test on 2018-01-01" in response.data assert b"test\nbody" in response.data assert b'href="/1/update"' in response.data @pytest.mark.parametrize("path", ("/create", "/1/update", "/1/delete")) def test_login_required(client, path): response = client.post(path) assert response.headers["Location"] == "/auth/login" def test_author_required(app, client, auth): # change the post author to another user with app.app_context(): db = get_db() db.execute("UPDATE post SET author_id = 2 WHERE id = 1") db.commit() auth.login() # current user can't modify other user's post assert client.post("/1/update").status_code == 403 assert client.post("/1/delete").status_code == 403 # current user doesn't see edit link assert b'href="/1/update"' not in client.get("/").data @pytest.mark.parametrize("path", ("/2/update", "/2/delete")) def test_exists_required(client, auth, path): auth.login() assert client.post(path).status_code == 404 def test_create(client, auth, app): auth.login() assert client.get("/create").status_code == 200 client.post("/create", data={"title": "created", "body": ""}) with app.app_context(): db = get_db() count = db.execute("SELECT COUNT(id) FROM post").fetchone()[0] assert count == 2 def test_update(client, auth, app): auth.login() assert client.get("/1/update").status_code == 200 client.post("/1/update", data={"title": "updated", "body": ""}) with app.app_context(): db = get_db() post = db.execute("SELECT * FROM post WHERE id = 1").fetchone() assert post["title"] == "updated" @pytest.mark.parametrize("path", ("/create", "/1/update")) def test_create_update_validate(client, auth, path): auth.login() response = client.post(path, data={"title": "", "body": ""}) assert b"Title is required." in response.data def test_delete(client, auth, app): auth.login() response = client.post("/1/delete") assert response.headers["Location"] == "/" with app.app_context(): db = get_db() post = db.execute("SELECT * FROM post WHERE id = 1").fetchone() assert post is None
                                                                                  flask - test auth
                                                                                  Pythondot imgLines of Code : 46dot imgLicense : Non-SPDX (BSD 3-Clause "New" or "Revised" License)
                                                                                  copy iconCopy
                                                                                  
                                                                                                                      import pytest from flask import g from flask import session from flaskr.db import get_db def test_register(client, app): # test that viewing the page renders without template errors assert client.get("/auth/register").status_code == 200 # test that successful registration redirects to the login page response = client.post("/auth/register", data={"username": "a", "password": "a"}) assert response.headers["Location"] == "/auth/login" # test that the user was inserted into the database with app.app_context(): assert ( get_db().execute("SELECT * FROM user WHERE username = 'a'").fetchone() is not None ) @pytest.mark.parametrize( ("username", "password", "message"), ( ("", "", b"Username is required."), ("a", "", b"Password is required."), ("test", "test", b"already registered"), ), ) def test_register_validate_input(client, username, password, message): response = client.post( "/auth/register", data={"username": username, "password": password} ) assert message in response.data def test_login(client, auth): # test that viewing the page renders without template errors assert client.get("/auth/login").status_code == 200 # test that successful login redirects to the index page response = auth.login() assert response.headers["Location"] == "/" # login request set the user_id in the session # check that the user is loaded from the session with client: client.get("/") assert session["user_id"] == 1 assert g.user["username"] == "test" @pytest.mark.parametrize( ("username", "password", "message"), (("a", "test", b"Incorrect username."), ("test", "a", b"Incorrect password.")), ) def test_login_validate_input(auth, username, password, message): response = auth.login(username, password) assert message in response.data def test_logout(client, auth): auth.login() with client: auth.logout() assert "user_id" not in session
                                                                                  Can I add two classes to an element in html in other places?
                                                                                  Pythondot imgLines of Code : 2dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                  copy iconCopy
                                                                                • How to make flask handle 25k request per second like express.js
                                                                                  Pythondot imgLines of Code : 5dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                  copy iconCopy
                                                                                  gunicorn -w 4 --threads 100 -b 0.0.0.0:5000 your_project:app
                                                                                  
                                                                                  pip install gevent
                                                                                  gunicorn -w 4 -k gevent --worker-connections 1000 -b 0.0.0.0:5000 your_project:app
                                                                                  
                                                                                  make every function of a file start with the same call to an external function
                                                                                  Pythondot imgLines of Code : 19dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                  copy iconCopy
                                                                                  def verified():
                                                                                      print('verified')
                                                                                      return False
                                                                                  
                                                                                  def redirect():
                                                                                      print('redirect')
                                                                                  
                                                                                  def verify(func):
                                                                                      if verified():
                                                                                          return func
                                                                                      else:
                                                                                          return redirect
                                                                                  
                                                                                  
                                                                                  @verify
                                                                                  def myfunc():
                                                                                      print('myfunc')
                                                                                  myfunc()
                                                                                  
                                                                                  Why does my data come from request.form when passing it to the backend in Flask, python?
                                                                                  Pythondot imgLines of Code : 50dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                  copy iconCopy
                                                                                  @socketio.on('receiver')
                                                                                  def message_server(msg):
                                                                                    /* Do something here */
                                                                                  
                                                                                   
                                                                                  /* You need to load socketio, you can look it up at socket.io, the link above also have instructions */
                                                                                   ​let​ ​socket​ ​=​ ​io​(​) 
                                                                                    
                                                                                    
                                                                                   ​  ​socket​.​emit​(​"receiver"​,​ ​{ 
                                                                                   ​    ​msg​: ​form​.​value​ /* your data */, 
                                                                                   ​  ​}​) 
                                                                                   ​   
                                                                                  
                                                                                    fetch(`${window.origin}/your_url`, {
                                                                                      method: "POST",
                                                                                      credentials: "include",
                                                                                      body: JSON.stringify(your_data),
                                                                                      cache: "no-cache",
                                                                                      headers: new Headers({
                                                                                        "content-type": "application/json"
                                                                                      })
                                                                                    })
                                                                                  
                                                                                  @app.route("/your_url", methods = ["post"])
                                                                                  def printer():
                                                                                    data = request.get_json()
                                                                                    print(data)
                                                                                    
                                                                                    return "hey"
                                                                                  
                                                                                  
                                                                                  
                                                                                  
                                                                                  
                                                                                  
                                                                                   Send Data 
                                                                                  
                                                                                  
                                                                                  
                                                                                  
                                                                                  @app.route("/your_url")
                                                                                  def your_function():
                                                                                      your_variable = request.form["name_of_the_input"]
                                                                                  
                                                                                  @app.route("/hello/")
                                                                                  def your_function(variable):
                                                                                      data = variable
                                                                                      .... ....
                                                                                  
                                                                                  Community Discussions

                                                                                  Trending Discussions on flask

                                                                                  Python/Docker ImportError: cannot import name 'json' from itsdangerous
                                                                                  chevron right
                                                                                  TypeError: __init__() got an unexpected keyword argument 'as_tuple'
                                                                                  chevron right
                                                                                  in VS Code ImportError: cannot import name 'Mapping' from 'collections'
                                                                                  chevron right
                                                                                  How to set schema_translate_map in SQLAlchemy object in Flask app
                                                                                  chevron right
                                                                                  WebSocket not working when trying to send generated answer by keras
                                                                                  chevron right
                                                                                  Google app engine deployment fails- Error while finding module specification for 'pip' (AttributeError: module '__main__' has no attribute '__file__')
                                                                                  chevron right
                                                                                  localhost:5000 unavailable in macOS v12 (Monterey)
                                                                                  chevron right
                                                                                  SQLAlchemy - Adding a ForeignKeyConstraint to a many-to-many table that is based on another relationship
                                                                                  chevron right
                                                                                  Cloud Run Flask API container running shutit enters a sleep loop
                                                                                  chevron right
                                                                                  Create a database trigger in an event listener
                                                                                  chevron right

                                                                                  QUESTION

                                                                                  Python/Docker ImportError: cannot import name 'json' from itsdangerous
                                                                                  Asked 2022-Mar-31 at 12:49

                                                                                  I am trying to get a Flask and Docker application to work but when I try and run it using my docker-compose up command in my Visual Studio terminal, it gives me an ImportError called ImportError: cannot import name 'json' from itsdangerous. I have tried to look for possible solutions to this problem but as of right now there are not many on here or anywhere else. The only two solutions I could find are to change the current installation of MarkupSafe and itsdangerous to a higher version: https://serverfault.com/questions/1094062/from-itsdangerous-import-json-as-json-importerror-cannot-import-name-json-fr and another one on GitHub that tells me to essentially change the MarkUpSafe and itsdangerous installation again https://github.com/aws/aws-sam-cli/issues/3661, I have also tried to make a virtual environment named veganetworkscriptenv to install the packages but that has also failed as well. I am currently using Flask 2.0.0 and Docker 5.0.0 and the error occurs on line eight in vegamain.py.

                                                                                  Here is the full ImportError that I get when I try and run the program:

                                                                                  veganetworkscript-backend-1  | Traceback (most recent call last):
                                                                                  veganetworkscript-backend-1  |   File "/app/vegamain.py", line 8, in 
                                                                                  veganetworkscript-backend-1  |     from flask import Flask
                                                                                  veganetworkscript-backend-1  |   File "/usr/local/lib/python3.9/site-packages/flask/__init__.py", line 19, in 
                                                                                  veganetworkscript-backend-1  |     from . import json
                                                                                  veganetworkscript-backend-1  |   File "/usr/local/lib/python3.9/site-packages/flask/json/__init__.py", line 15, in 
                                                                                  veganetworkscript-backend-1  |     from itsdangerous import json as _json
                                                                                  veganetworkscript-backend-1  | ImportError: cannot import name 'json' from 'itsdangerous' (/usr/local/lib/python3.9/site-packages/itsdangerous/__init__.py)
                                                                                  veganetworkscript-backend-1 exited with code 1
                                                                                  

                                                                                  Here are my requirements.txt, vegamain.py, Dockerfile, and docker-compose.yml files:

                                                                                  requirements.txt:

                                                                                  Flask==2.0.0
                                                                                  Flask-SQLAlchemy==2.4.4
                                                                                  SQLAlchemy==1.3.20
                                                                                  Flask-Migrate==2.5.3
                                                                                  Flask-Script==2.0.6
                                                                                  Flask-Cors==3.0.9
                                                                                  requests==2.25.0
                                                                                  mysqlclient==2.0.1
                                                                                  pika==1.1.0
                                                                                  wolframalpha==4.3.0
                                                                                  

                                                                                  vegamain.py:

                                                                                  # Veganetwork (C) TetraSystemSolutions 2022
                                                                                  # all rights are reserved.  
                                                                                  # 
                                                                                  # Author: Trevor R. Blanchard Feb-19-2022-Jul-30-2022
                                                                                  #
                                                                                  
                                                                                  # get our imports in order first
                                                                                  from flask import Flask # <-- error occurs here!!!
                                                                                  
                                                                                  # start the application through flask.
                                                                                  app = Flask(__name__)
                                                                                  
                                                                                  # if set to true will return only a "Hello World" string.
                                                                                  Debug = True
                                                                                  
                                                                                  # start a route to the index part of the app in flask.
                                                                                  @app.route('/')
                                                                                  def index():
                                                                                      if (Debug == True):
                                                                                          return 'Hello World!'
                                                                                      else:
                                                                                          pass
                                                                                  
                                                                                  # start the flask app here --->
                                                                                  if __name__ == '__main__':
                                                                                      app.run(debug=True, host='0.0.0.0') 
                                                                                  

                                                                                  Dockerfile:

                                                                                  FROM python:3.9
                                                                                  ENV PYTHONUNBUFFERED 1
                                                                                  WORKDIR /app
                                                                                  COPY requirements.txt /app/requirements.txt
                                                                                  RUN pip install -r requirements.txt
                                                                                  COPY . /app
                                                                                  

                                                                                  docker-compose.yml:

                                                                                  version: '3.8'
                                                                                  services:
                                                                                    backend:
                                                                                      build:
                                                                                        context: .
                                                                                        dockerfile: Dockerfile
                                                                                      command: 'python vegamain.py'
                                                                                      ports:
                                                                                        - 8004:5000
                                                                                      volumes:
                                                                                        - .:/app
                                                                                      depends_on:
                                                                                        - db
                                                                                  
                                                                                  #  queue:
                                                                                  #    build:
                                                                                  #      context: .
                                                                                  #      dockerfile: Dockerfile
                                                                                  #    command: 'python -u consumer.py'
                                                                                  #    depends_on:
                                                                                  #      - db
                                                                                  
                                                                                    db:
                                                                                      image: mysql:5.7.22
                                                                                      restart: always
                                                                                      environment:
                                                                                        MYSQL_DATABASE: admin
                                                                                        MYSQL_USER: root
                                                                                        MYSQL_PASSWORD: root
                                                                                        MYSQL_ROOT_PASSWORD: root
                                                                                      volumes:
                                                                                        - .dbdata:/var/lib/mysql
                                                                                      ports:
                                                                                        - 33069:3306
                                                                                  

                                                                                  How exactly can I fix this code? thank you!

                                                                                  ANSWER

                                                                                  Answered 2022-Feb-20 at 12:31

                                                                                  I was facing the same issue while running docker containers with flask.

                                                                                  I downgraded Flask to 1.1.4 and markupsafe to 2.0.1 which solved my issue.

                                                                                  Check this for reference.

                                                                                  Source https://stackoverflow.com/questions/71189819

                                                                                  QUESTION

                                                                                  TypeError: __init__() got an unexpected keyword argument 'as_tuple'
                                                                                  Asked 2022-Mar-29 at 23:24

                                                                                  While I am testing my API I recently started to get the error below.

                                                                                          if request is None:
                                                                                  >           builder = EnvironBuilder(*args, **kwargs)
                                                                                  E           TypeError: __init__() got an unexpected keyword argument 'as_tuple'
                                                                                  
                                                                                  /usr/local/lib/python3.7/site-packages/werkzeug/test.py:1081: TypeError
                                                                                  

                                                                                  As I read from the documentation in the newer version of Werkzeug the as_tuple parameter is removed.

                                                                                  Part of my test code is

                                                                                  
                                                                                  from flask.testing import FlaskClient
                                                                                  
                                                                                  @pytest.fixture(name='test_client')
                                                                                  def _test_client() -> FlaskClient:
                                                                                      app = create_app()
                                                                                      return app.test_client()
                                                                                  
                                                                                  
                                                                                  class TestPeerscoutAPI:
                                                                                      def test_should_have_access_for_status_page(self, test_client: FlaskClient):
                                                                                          response = test_client.get('/api/status')
                                                                                          assert _get_ok_json(response) == {"status": "OK"}
                                                                                  

                                                                                  Any help would be greatly appreciated.

                                                                                  ANSWER

                                                                                  Answered 2022-Mar-29 at 13:29

                                                                                  As of version 2.1.0, werkzeug has removed the as_tuple argument to Client. Since Flask wraps werkzeug and you're using a version that still passes this argument, it will fail. See the exact change on the GitHub PR here.

                                                                                  You can take one of two paths to solve this:

                                                                                  1. Upgrade flask

                                                                                  2. Pin your werkzeug version

                                                                                  # in requirements.txt
                                                                                  werkzeug==2.0.3
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/71661851

                                                                                  QUESTION

                                                                                  in VS Code ImportError: cannot import name 'Mapping' from 'collections'
                                                                                  Asked 2022-Mar-24 at 11:58

                                                                                  I am trying to connect to Postgress and create a folder test.db via Flask. When I run "python3" in the terminal and from there when I run "from app import db" I get an import error:

                                                                                  ImportError: cannot import name 'Mapping' from 'collections' (/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/collections/__init__.py)
                                                                                  

                                                                                  I have tried all the troubleshooting but none of them worked. Please advise. Here is the full stack: full stack error

                                                                                  ANSWER

                                                                                  Answered 2021-Oct-11 at 10:45

                                                                                  Use older version of python (eg 3.8)

                                                                                  Source https://stackoverflow.com/questions/69381312

                                                                                  QUESTION

                                                                                  How to set schema_translate_map in SQLAlchemy object in Flask app
                                                                                  Asked 2022-Feb-19 at 23:10

                                                                                  My app.py file

                                                                                  from flask import Flask
                                                                                  from flask_sqlalchemy import SQLAlchemy
                                                                                  
                                                                                  from flask import Flask
                                                                                  from flask_sqlalchemy import SQLAlchemy
                                                                                  
                                                                                  app = Flask(__name__)
                                                                                  app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres:////tmp/test.db'
                                                                                  db = SQLAlchemy(app) # refer https://flask-sqlalchemy.palletsprojects.com/en/2.x/api/#flask_sqlalchemy.SQLAlchemy
                                                                                  

                                                                                  One of my model classes, where I imported db

                                                                                  from app import db
                                                                                  Base = declarative_base()
                                                                                  
                                                                                  # User class
                                                                                  class User(db.Model, Base):
                                                                                    id = db.Column(db.Integer, primary_key=True)
                                                                                    username = db.Column(db.String(80), unique=True, nullable=False)
                                                                                    email = db.Column(db.String(120), unique=True, nullable=False)
                                                                                  
                                                                                    def __repr__(self):
                                                                                      return '' % self.username
                                                                                  
                                                                                    def get_user_by_id(self, id):
                                                                                      return self.query.get(id)
                                                                                  

                                                                                  My database has the same set of tables in different schema (multi-tenancy) and there I need to select the schema as per the request initiated by a particular tenant on the fly by using before_request (grabbing tenant_id from subdomain URL).

                                                                                  I found Postgres provides selecting the schema name on fly by using schema_translate_map ref. https://docs.sqlalchemy.org/en/14/core/connections.html#translation-of-schema-names and that is under execution_options https://docs.sqlalchemy.org/en/14/core/connections.html#sqlalchemy.engine.Connection.execution_options

                                                                                  In my above code snippet where you see db = SQLAlchemy(app), as per official documentation, two parameters can be set in SQLAlchemy objct creation and they are - session_options and engine_options, but no execution_options ref. https://flask-sqlalchemy.palletsprojects.com/en/2.x/api/#flask_sqlalchemy.SQLAlchemy

                                                                                  But how do I set schema_translate_map setting when I am creating an object of SQLAlchemy

                                                                                  I tried this -

                                                                                  db = SQLAlchemy(app, 
                                                                                    session_options={
                                                                                      "autocommit": True, 
                                                                                      "autoflush": False, 
                                                                                      "schema_translate_map": {
                                                                                        None: "public"
                                                                                      }
                                                                                    }
                                                                                  )
                                                                                  

                                                                                  But obviously, it did not work, because schema_translate_map is under execution_options as mentioned here https://docs.sqlalchemy.org/en/14/core/connections.html#translation-of-schema-names

                                                                                  Anyone has an idea, how to set schema_translate_map at the time of creating SQLAlchemy object.

                                                                                  My goal is to set it dynamically for each request. I want to control it from this centralized place, rather than going in each model file and specifying it when I execute queries.

                                                                                  I am aware of doing this differently as suggested here https://stackoverflow.com/a/56490246/1560470 but my need is to set somewhere around db = SQLAlchemy(app) in app.py file only. Then after I import db in all my model classes (as shown above) and in those model classes, all queries execute under the selected schema.

                                                                                  ANSWER

                                                                                  Answered 2022-Feb-19 at 23:10

                                                                                  I found a way to accomplish it. This is what needed

                                                                                  db = SQLAlchemy(app, 
                                                                                    session_options={
                                                                                      "autocommit": True, 
                                                                                      "autoflush": False
                                                                                    },
                                                                                    engine_options={
                                                                                      "execution_options":
                                                                                        {
                                                                                          "schema_translate_map": {
                                                                                            None: "public",
                                                                                            "abc": "xyz"
                                                                                          }
                                                                                        }
                                                                                    }
                                                                                  )
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/71099132

                                                                                  QUESTION

                                                                                  WebSocket not working when trying to send generated answer by keras
                                                                                  Asked 2022-Feb-17 at 12:52

                                                                                  I am implementing a simple chatbot using keras and WebSockets. I now have a model that can make a prediction about the user input and send the according answer.

                                                                                  When I do it through command line it works fine, however when I try to send the answer through my WebSocket, the WebSocket doesn't even start anymore.

                                                                                  Here is my working WebSocket code:

                                                                                  @sock.route('/api')
                                                                                  def echo(sock):
                                                                                      while True:
                                                                                          # get user input from browser
                                                                                          user_input = sock.receive()
                                                                                          # print user input on console
                                                                                          print(user_input)
                                                                                          # read answer from console
                                                                                          response = input()
                                                                                          # send response to browser
                                                                                          sock.send(response)
                                                                                  

                                                                                  Here is my code to communicate with the keras model on command line:

                                                                                  while True:
                                                                                      question = input("")
                                                                                      ints = predict(question)
                                                                                      answer = response(ints, json_data)
                                                                                      print(answer)
                                                                                  

                                                                                  Used methods are those:

                                                                                  def predict(sentence):
                                                                                      bag_of_words = convert_sentence_in_bag_of_words(sentence)
                                                                                      # pass bag as list and get index 0
                                                                                      prediction = model.predict(np.array([bag_of_words]))[0]
                                                                                      ERROR_THRESHOLD = 0.25
                                                                                      accepted_results = [[tag, probability] for tag, probability in enumerate(prediction) if probability > ERROR_THRESHOLD]
                                                                                  
                                                                                      accepted_results.sort(key=lambda x: x[1], reverse=True)
                                                                                  
                                                                                      output = []
                                                                                      for accepted_result in accepted_results:
                                                                                          output.append({'intent': classes[accepted_result[0]], 'probability': str(accepted_result[1])})
                                                                                          print(output)
                                                                                      return output
                                                                                  
                                                                                  
                                                                                  def response(intents, json):
                                                                                      tag = intents[0]['intent']
                                                                                      intents_as_list = json['intents']
                                                                                      for i in intents_as_list:
                                                                                          if i['tag'] == tag:
                                                                                              res = random.choice(i['responses'])
                                                                                              break
                                                                                      return res
                                                                                  

                                                                                  So when I start the WebSocket with the working code I get this output:

                                                                                   * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
                                                                                   * Restarting with stat
                                                                                   * Serving Flask app 'server' (lazy loading)
                                                                                   * Environment: production
                                                                                     WARNING: This is a development server. Do not use it in a production deployment.
                                                                                     Use a production WSGI server instead.
                                                                                   * Debug mode: on
                                                                                  

                                                                                  But as soon as I have anything of my model in the server.py class I get this output:

                                                                                  2022-02-13 11:31:38.887640: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:305] Could not identify NUMA node of platform GPU ID 0, defaulting to 0. Your kernel may not have been built with NUMA support.
                                                                                  2022-02-13 11:31:38.887734: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:271] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 0 MB memory) -> physical PluggableDevice (device: 0, name: METAL, pci bus id: )
                                                                                  Metal device set to: Apple M1
                                                                                  
                                                                                  systemMemory: 16.00 GB
                                                                                  maxCacheSize: 5.33 GB
                                                                                  

                                                                                  It is enough when I just have an import at the top like this: from chatty import response, predict - even though they are unused.

                                                                                  ANSWER

                                                                                  Answered 2022-Feb-16 at 19:53

                                                                                  There is no problem with your websocket route. Could you please share how you are triggering this route? Websocket is a different protocol and I'm suspecting that you are using a HTTP client to test websocket. For example in Postman:

                                                                                  Postman New Screen

                                                                                  HTTP requests are different than websocket requests. So, you should use appropriate client to test websocket.

                                                                                  Source https://stackoverflow.com/questions/71099818

                                                                                  QUESTION

                                                                                  Google app engine deployment fails- Error while finding module specification for 'pip' (AttributeError: module '__main__' has no attribute '__file__')
                                                                                  Asked 2022-Jan-08 at 22:02

                                                                                  We are using command prompt c:\gcloud app deploy app.yaml, but get the following error:

                                                                                  Running "python3 -m pip install --requirement requirements.txt --upgrade --upgrade-strategy only-if-needed --no-warn-script-location --no-warn-conflicts --force-reinstall --no-compile (PIP_CACHE_DIR=/layers/google.python.pip/pipcache PIP_DISABLE_PIP_VERSION_CHECK=1)"
                                                                                  Step #2 - "build": /layers/google.python.pip/pip/bin/python3: Error while finding module specification for 'pip' (AttributeError: module '__main__' has no attribute '__file__')
                                                                                  Step #2 - "build": Done "python3 -m pip install --requirement requirements.txt --upgr..." (34.49892ms)
                                                                                  Step #2 - "build": Failure: (ID: 0ea8a540) /layers/google.python.pip/pip/bin/python3: Error while finding module specification for 'pip' (AttributeError: module '__main__' has no attribute '__file__')
                                                                                  Step #2 - "build": --------------------------------------------------------------------------------
                                                                                  Step #2 - "build": Running "mv -f /builder/outputs/output-5577006791947779410 /builder/outputs/output"
                                                                                  Step #2 - "build": Done "mv -f /builder/outputs/output-5577006791947779410 /builder/o..." (12.758866ms)
                                                                                  Step #2 - "build": ERROR: failed to build: exit status 1
                                                                                  Finished Step #2 - "build"
                                                                                  ERROR
                                                                                  ERROR: build step 2 "us.gcr.io/gae-runtimes/buildpacks/python37/builder:python37_20211201_3_7_12_RC00" failed: step exited with non-zero status: 145
                                                                                  

                                                                                  Our Requirements.txt is as below. We are currently on Python 3.7 standard app engine

                                                                                  firebase_admin==3.0.0
                                                                                  sendgrid==6.9.3
                                                                                  google-auth==1.35.0
                                                                                  google-auth-httplib2==0.1.0
                                                                                  jinja2==3.0.3
                                                                                  MarkupSafe==2.0.1
                                                                                  pytz==2021.3
                                                                                  Flask==2.0.2
                                                                                  twilio==6.46.0
                                                                                  httplib2==0.20.2
                                                                                  requests==2.24.0
                                                                                  requests_toolbelt==0.9.1
                                                                                  google-cloud-tasks==2.7.1
                                                                                  google-cloud-logging==1.15.1
                                                                                  googleapis-common-protos==1.54.0
                                                                                  

                                                                                  Please help.The above code was working well before updating the requirements.txt file. We tried to remove gunicorn to allow the system pickup the latest according to documentation here.

                                                                                  We have a subdirectory structure that stores all the .py files in controllers and db definitions in models. Our main.py has the following -

                                                                                  sys.path.append(os.path.join(os.path.dirname(__file__), '../controllers'))
                                                                                  sys.path.append(os.path.join(os.path.dirname(__file__), '../models'))
                                                                                  

                                                                                  Does anyone know how to debug this error - Error while finding module specification for 'pip' (AttributeError: module '__main__' has no attribute '__file__'). What does this mean?

                                                                                  ANSWER

                                                                                  Answered 2022-Jan-06 at 09:24

                                                                                  Your setuptools version is likely to be yanked:

                                                                                  https://pypi.org/project/setuptools/60.3.0/

                                                                                  Not sure how to fix that without a working pip though.

                                                                                  Source https://stackoverflow.com/questions/70602290

                                                                                  QUESTION

                                                                                  localhost:5000 unavailable in macOS v12 (Monterey)
                                                                                  Asked 2021-Dec-08 at 14:08

                                                                                  I cannot access a web server on localhost port 5000 on macOS v12 (Monterey) (Flask or any other).

                                                                                  E.g., use the built-in HTTP server, I cannot get onto port 5000:

                                                                                  python3 -m http.server 5000
                                                                                  
                                                                                  ... (stack trace)
                                                                                  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 466, in server_bind
                                                                                  self.socket.bind(self.server_address)
                                                                                  OSError: [Errno 48] Address already in use
                                                                                  

                                                                                  If you have Flask installed and you run the Flask web server, it does not fail on start. Let's take the minimum Flask example code:

                                                                                  # Save as hello.py in the current working directory.
                                                                                  from flask import Flask
                                                                                  app = Flask(__name__)
                                                                                  @app.route("/")
                                                                                  def hello_world():
                                                                                      return "

                                                                                  Hello, World!

                                                                                  "

                                                                                  Then run it (provided you have Flask/Python 3 installed):

                                                                                  export FLASK_APP=hello
                                                                                  flask run
                                                                                  

                                                                                  Output:

                                                                                  * Running on http://127.0.0.1:5000/
                                                                                  

                                                                                  However, if you try to access this server (from a browser or with anything else), it is denied:

                                                                                  curl -I localhost:5000
                                                                                  HTTP/1.1 403 Forbidden
                                                                                  Content-Length: 0
                                                                                  Server: AirTunes/595.13.1
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2021-Dec-08 at 14:08

                                                                                  macOS Monterey introduced AirPlay Receiver running on port 5000. This prevents your web server from serving on port 5000. Receiver already has the port.

                                                                                  You can either:

                                                                                  1. turn off AirPlay Receiver, or;
                                                                                  2. run the server on a different port (normally best).

                                                                                  Turn off AirPlay Receiver

                                                                                  Go to System PreferencesSharingUntick Airplay Receiver.

                                                                                  See more details

                                                                                  You should be able to rerun the server now on port 5000 and get a response:

                                                                                  python3 -m http.server 5000
                                                                                  
                                                                                  Serving HTTP on :: port 5000 (http://[::]:5000/) ...
                                                                                  

                                                                                  Run the server on a different port than 5000

                                                                                  It's probably a better idea to no longer use port 5000 as that's reserved for Airplay Receiver on macOS Monterey.

                                                                                  Just to run the server on a different port. There isn't any need to turn off Airplay Receiver.

                                                                                  python3 -m http.server 4999
                                                                                  

                                                                                  or

                                                                                  export FLASK_APP=hello
                                                                                  flask run -p 4999
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/69818376

                                                                                  QUESTION

                                                                                  SQLAlchemy - Adding a ForeignKeyConstraint to a many-to-many table that is based on another relationship
                                                                                  Asked 2021-Oct-11 at 01:42

                                                                                  Forgive me if this has been answered elsewhere. I've been searching SO and haven't been able to translate the seemingly relevant Q&As to my scenerio.

                                                                                  I'm working on a fun personal project where I have 4 main schemas (barring relationships for now):

                                                                                  • Persona (name, bio)
                                                                                  • Episode (title, plot)
                                                                                  • Clip (url, timestamp)
                                                                                  • Image (url)

                                                                                  Restrictions (Basis of Relationships):

                                                                                  1. A Persona can show up in multiple episodes, as well as multiple clips and images from those episodes (but might not be in all clips/images related to an episode).
                                                                                  2. An Episode can contain multiple personas, clips, and images.
                                                                                  3. An Image/Clip can only be related to a single Episode, but can be related to multiple personas.
                                                                                  4. If a Persona is already assigned to episode(s), then any clip/image assigned to the persona can only be from one of those episodes or (if new) must only be capable of having one of the episodes that the persona appeared in associated to the clip/image.
                                                                                  5. If an Episode is already assigned persona(s), then any clip/image assigned to the episode must be related to aleast one of those personas or (if new) must only be capable of having one or more of the personas from the episode associated to the clip/image.

                                                                                  I've designed the database structure like so:

                                                                                  This generates the following sql:

                                                                                  DROP TABLE IF EXISTS episodes;
                                                                                  DROP TABLE IF EXISTS personas;
                                                                                  DROP TABLE IF EXISTS personas_episodes;
                                                                                  DROP TABLE IF EXISTS clips;
                                                                                  DROP TABLE IF EXISTS personas_clips;
                                                                                  DROP TABLE IF EXISTS images;
                                                                                  DROP TABLE IF EXISTS personas_images;
                                                                                  
                                                                                  
                                                                                  CREATE TABLE episodes (
                                                                                  id INT NOT NULL PRIMARY KEY,
                                                                                  title VARCHAR(120) NOT NULL UNIQUE,
                                                                                  plot TEXT,
                                                                                  tmdb_id VARCHAR(10) NOT NULL,
                                                                                  tvdb_id VARCHAR(10) NOT NULL,
                                                                                  imdb_id VARCHAR(10) NOT NULL);
                                                                                  
                                                                                  CREATE TABLE personas (
                                                                                  id INT NOT NULL PRIMARY KEY,
                                                                                  name VARCHAR(30) NOT NULL,
                                                                                  bio TEXT NOT NULL);
                                                                                  
                                                                                  CREATE TABLE personas_episodes (
                                                                                  persona_id INT NOT NULL,
                                                                                  episode_id INT NOT NULL,
                                                                                  PRIMARY KEY (persona_id,episode_id),
                                                                                  FOREIGN KEY(persona_id) REFERENCES personas(id),
                                                                                  FOREIGN KEY(episode_id) REFERENCES episodes(id));
                                                                                  
                                                                                  CREATE TABLE clips (
                                                                                  id INT NOT NULL PRIMARY KEY,
                                                                                  title VARCHAR(100) NOT NULL,
                                                                                  timestamp VARCHAR(7) NOT NULL,
                                                                                  link VARCHAR(100) NOT NULL,
                                                                                  episode_id INT NOT NULL,
                                                                                  FOREIGN KEY(episode_id) REFERENCES episodes(id));
                                                                                  
                                                                                  CREATE TABLE personas_clips (
                                                                                  clip_id INT NOT NULL,
                                                                                  persona_id INT NOT NULL,
                                                                                  PRIMARY KEY (clip_id,persona_id),
                                                                                  FOREIGN KEY(clip_id) REFERENCES clips(id),
                                                                                  FOREIGN KEY(persona_id) REFERENCES personas(id));
                                                                                  
                                                                                  CREATE TABLE images (
                                                                                  id INT NOT NULL PRIMARY KEY,
                                                                                  link VARCHAR(120) NOT NULL UNIQUE,
                                                                                  path VARCHAR(120) NOT NULL UNIQUE,
                                                                                  episode_id INT NOT NULL,
                                                                                  FOREIGN KEY(episode_id) REFERENCES episodes(id));
                                                                                  
                                                                                  CREATE TABLE personas_images (
                                                                                  persona_id INT NOT NULL,
                                                                                  image_id INT NOT NULL,
                                                                                  PRIMARY KEY (persona_id,image_id),
                                                                                  FOREIGN KEY(persona_id) REFERENCES personas(id),
                                                                                  FOREIGN KEY(image_id) REFERENCES images(id));
                                                                                  

                                                                                  And I've attempted to create the same schema in SQLAchemy models (keeping in mind SQLite for testing, PostgreSQL for production) like so:

                                                                                  # db is a configured Flask-SQLAlchemy instance
                                                                                  from app import db
                                                                                  # Alias common SQLAlchemy names
                                                                                  Column = db.Column
                                                                                  relationship = db.relationship
                                                                                  
                                                                                  
                                                                                  class PkModel(Model):
                                                                                      """Base model class that adds a 'primary key' column named ``id``."""
                                                                                   
                                                                                      __abstract__ = True
                                                                                      id = Column(db.Integer, primary_key=True)
                                                                                   
                                                                                   
                                                                                  def reference_col(
                                                                                      tablename, nullable=False, pk_name="id", foreign_key_kwargs=None, column_kwargs=None
                                                                                  ):
                                                                                      """Column that adds primary key foreign key reference.
                                                                                   
                                                                                      Usage: ::
                                                                                   
                                                                                          category_id = reference_col('category')
                                                                                          category = relationship('Category', backref='categories')
                                                                                      """
                                                                                      foreign_key_kwargs = foreign_key_kwargs or {}
                                                                                      column_kwargs = column_kwargs or {}
                                                                                   
                                                                                      return Column(
                                                                                          db.ForeignKey(f"{tablename}.{pk_name}", **foreign_key_kwargs),
                                                                                          nullable=nullable,
                                                                                          **column_kwargs,
                                                                                      )
                                                                                  
                                                                                  personas_episodes = db.Table(
                                                                                      "personas_episodes",
                                                                                      db.Column("persona_id", db.ForeignKey("personas.id"), primary_key=True),
                                                                                      db.Column("episode_id", db.ForeignKey("episodes.id"), primary_key=True),
                                                                                  )
                                                                                   
                                                                                  personas_clips = db.Table(
                                                                                      "personas_clips",
                                                                                      db.Column("persona_id", db.ForeignKey("personas.id"), primary_key=True),
                                                                                      db.Column("clip_id", db.ForeignKey("clips.id"), primary_key=True),
                                                                                  )
                                                                                   
                                                                                  personas_images = db.Table(
                                                                                      "personas_images",
                                                                                      db.Column("persona_id", db.ForeignKey("personas.id"), primary_key=True),
                                                                                      db.Column("image_id", db.ForeignKey("images.id"), primary_key=True),
                                                                                  )
                                                                                   
                                                                                   
                                                                                  class Persona(PkModel):
                                                                                      """One of Roger's personas."""
                                                                                   
                                                                                      __tablename__ = "personas"
                                                                                      name = Column(db.String(80), unique=True, nullable=False)
                                                                                      bio = Column(db.Text)
                                                                                      # relationships
                                                                                      episodes = relationship("Episode", secondary=personas_episodes, back_populates="personas")
                                                                                      clips = relationship("Clip", secondary=personas_clips, back_populates="personas")
                                                                                      images = relationship("Image", secondary=personas_images, back_populates="personas")
                                                                                   
                                                                                      def __repr__(self):
                                                                                          """Represent instance as a unique string."""
                                                                                          return f""
                                                                                   
                                                                                   
                                                                                  class Image(PkModel):
                                                                                      """An image of one of Roger's personas from an episode of American Dad."""
                                                                                      
                                                                                      __tablename__ = "images"
                                                                                      link = Column(db.String(120), unique=True)
                                                                                      path = Column(db.String(120), unique=True)
                                                                                      episode_id = reference_col("episodes")
                                                                                      # relationships
                                                                                      personas = relationship("Persona", secondary=personas_images, back_populates="images")
                                                                                      
                                                                                   
                                                                                   
                                                                                  class Episode(PkModel):
                                                                                      """An episode of American Dad."""
                                                                                      
                                                                                      # FIXME: We can add Clips and Images linked to Personas that are not assigned to this episode
                                                                                   
                                                                                      __tablename__ = "episodes"
                                                                                      title = Column(db.String(120), unique=True, nullable=False)
                                                                                      plot = Column(db.Text)
                                                                                      tmdb_id = Column(db.String(10))
                                                                                      tvdb_id = Column(db.String(10))
                                                                                      imdb_id = Column(db.String(10))
                                                                                      # relationships
                                                                                      personas = relationship("Persona", secondary=personas_episodes, back_populates="episodes")
                                                                                      images = relationship("Image", backref="episode")
                                                                                      clips = relationship("Clip", backref="episode")
                                                                                   
                                                                                      def __repr__(self):
                                                                                          """Represent instance as a unique string."""
                                                                                          return f""
                                                                                   
                                                                                   
                                                                                  class Clip(PkModel):
                                                                                      """A clip from an episode of American Dad that contains one or more of Roger's personas."""
                                                                                   
                                                                                      __tablename__ = "clips"
                                                                                      title = Column(db.String(80), unique=True, nullable=False)
                                                                                      timestamp = Column(db.String(7), nullable=True)  # 00M:00S
                                                                                      link = Column(db.String(7), nullable=True)
                                                                                      episode_id = reference_col("episodes")
                                                                                      # relationships
                                                                                      personas = relationship("Persona", secondary=personas_clips, back_populates="clips")
                                                                                  

                                                                                  However, notice the FIXME comment. I'm having trouble figuring out how to constrain the many-to-many relationships on personas+images, personas+clips, and personas+episodes in a way that they all look at each other before adding a new entry to restrict the possible additions to the subset of items that meet the criteria of those other many-to-many relationships.

                                                                                  Can someone please provide a solution to ensure the many-to-many relationships respect the episode_id relationship in the parent tables?

                                                                                  Edit to add pseudo model example of expected behavior

                                                                                  # omitting some detail fields for brevity
                                                                                  e1 = Episode(title="Some Episode")
                                                                                  e2 = Episode(title="Another Episode")
                                                                                  p1 = Persona(name="Raider Dave", episodes=[e1])
                                                                                  p2 = Persona(name="Ricky Spanish", episodes=[e2])
                                                                                  c1 = Clip(title="A clip", episode=e1, personas=[p2])  # should fail
                                                                                  i1 = Image(title="An image", episode=e2, personas=[p1]) # should fail
                                                                                  c2 = Clip(title="Another clip", episode=e1, personas=[p1])  # should succeed
                                                                                  i2 = Image(title="Another image", episode=e2, personas=[p2]) # should succeed
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2021-Oct-05 at 23:19

                                                                                  I can't think of any way to add this logic on the DB. Would it be acceptable to manage these constraints in your code? Like this:

                                                                                  Event: a new image would be insterted in DB

                                                                                  # create new image with id = 1 and linked episode = 1
                                                                                  my_image = Image(...) 
                                                                                  
                                                                                  # my personas
                                                                                  Persona.query.all()
                                                                                  [, , ]
                                                                                  
                                                                                  # my episodes
                                                                                  >>> Episode.query.all()
                                                                                  []
                                                                                  
                                                                                  #my images
                                                                                  >>> Image.query.all()
                                                                                  [, ]
                                                                                  
                                                                                  # personas in first image
                                                                                  >>> Image.query.all()[0].personas
                                                                                  []
                                                                                  
                                                                                  # which episode?
                                                                                  >>> Image.query.all()[0].episode
                                                                                  
                                                                                  
                                                                                  # same as above but with next personas (Note that Pikachu is linked to the wrong episode)
                                                                                  >>> Image.query.all()[1].personas
                                                                                  []
                                                                                  >>> Image.query.all()[1].episode
                                                                                  
                                                                                  
                                                                                  # before saving the Image object check its episode id, then for that episode get a list of personas that appear.
                                                                                  # Look for your persona id of Image inside this list to see if this persona appear in the episode
                                                                                  
                                                                                  my_image.episode.id # return 1
                                                                                  
                                                                                  # get a list of persona(s).id that appear in the episode linked to the image!
                                                                                  personas_in_episode = [ persona.id for persona in Episode.query.filter_by(id=1).first().personas ] # return list of id of Persona objects [1,2] (Homer and Marge as episode with id 1 is The Simpson)
                                                                                  
                                                                                  my_image_personas = [ persona.id for persona in my_image.personas ] # return a list of id of Persona objects linked in image [3] Persona is Pikachu
                                                                                  
                                                                                  >>> my_image_personas
                                                                                  [3]
                                                                                  
                                                                                  >>> for persona_id in my_image_personas:
                                                                                  ...     if persona_id not in personas_in_episode:
                                                                                  ...         print(f"persona with id {persona_id} does not appear in the episode for this image") 
                                                                                  ... 
                                                                                  persona with id 3 does not appear in the episode for this image
                                                                                  

                                                                                  The same goes for clip.

                                                                                  Source https://stackoverflow.com/questions/69418576

                                                                                  QUESTION

                                                                                  Cloud Run Flask API container running shutit enters a sleep loop
                                                                                  Asked 2021-Sep-30 at 14:13

                                                                                  The issue has appeared recently and the previously healthy container now enters a sleep loop when a shutit session is being created. The issue occurs only on Cloud Run and not locally.

                                                                                  Minimum reproducible code:

                                                                                  requirements.txt

                                                                                  Flask==2.0.1
                                                                                  gunicorn==20.1.0
                                                                                  shutit
                                                                                  

                                                                                  Dockerfile

                                                                                  FROM python:3.9
                                                                                  
                                                                                  # Allow statements and log messages to immediately appear in the Cloud Run logs
                                                                                  ENV PYTHONUNBUFFERED True
                                                                                  
                                                                                  COPY requirements.txt ./
                                                                                  RUN pip install -r requirements.txt
                                                                                  
                                                                                  # Copy local code to the container image.
                                                                                  ENV APP_HOME /myapp
                                                                                  WORKDIR $APP_HOME
                                                                                  COPY . ./
                                                                                  
                                                                                  CMD exec gunicorn \
                                                                                   --bind :$PORT \
                                                                                   --worker-class "sync" \
                                                                                   --workers 1 \
                                                                                   --threads 1 \
                                                                                   --timeout 0 \
                                                                                   main:app
                                                                                  

                                                                                  main.py

                                                                                  import os
                                                                                  import shutit
                                                                                  from flask import Flask, request
                                                                                  
                                                                                  app = Flask(__name__)
                                                                                  
                                                                                  # just to prove api works
                                                                                  @app.route('/ping', methods=['GET'])
                                                                                  def ping():
                                                                                      os.system('echo pong')
                                                                                      return 'OK'
                                                                                  
                                                                                  # issue replication
                                                                                  @app.route('/healthcheck', methods=['GET'])
                                                                                  def healthcheck():
                                                                                      os.system("echo 'healthcheck'")
                                                                                      # hangs inside create_session
                                                                                      shell = shutit.create_session(echo=True, loglevel='debug')
                                                                                      # never shell.send reached 
                                                                                      shell.send('echo Hello World', echo=True)
                                                                                      # never returned
                                                                                      return 'OK'
                                                                                  
                                                                                  if __name__ == '__main__':
                                                                                      app.run(host='127.0.0.1', port=8080, debug=True)
                                                                                  

                                                                                  cloudbuild.yaml

                                                                                  steps:
                                                                                    - id: "build_container"
                                                                                      name: "gcr.io/kaniko-project/executor:latest"
                                                                                      args:
                                                                                        - --destination=gcr.io/$PROJECT_ID/borked-service-debug:latest
                                                                                        - --cache=true
                                                                                        - --cache-ttl=99h
                                                                                    - id: "configure infrastructure"
                                                                                      name: "gcr.io/cloud-builders/gcloud"
                                                                                      entrypoint: "bash"
                                                                                      args:
                                                                                        - "-c"
                                                                                        - |
                                                                                          set -euxo pipefail
                                                                                  
                                                                                          REGION="europe-west1"
                                                                                          CLOUD_RUN_SERVICE="borked-service-debug"
                                                                                  
                                                                                          SA_NAME="$${CLOUD_RUN_SERVICE}@${PROJECT_ID}.iam.gserviceaccount.com"
                                                                                  
                                                                                          gcloud beta run deploy $${CLOUD_RUN_SERVICE} \
                                                                                            --service-account "$${SA_NAME}" \
                                                                                            --image gcr.io/${PROJECT_ID}/$${CLOUD_RUN_SERVICE}:latest \
                                                                                            --allow-unauthenticated \
                                                                                            --platform managed \
                                                                                            --concurrency 1 \
                                                                                            --max-instances 10 \
                                                                                            --timeout 1000s \
                                                                                            --cpu 1 \
                                                                                            --memory=1Gi \
                                                                                            --region "$${REGION}"
                                                                                  
                                                                                  

                                                                                  cloud run logs that get looped:

                                                                                  Setting up prompt
                                                                                  In session: host_child, trying to send: export PS1_ORIGIN_ENV=$PS1 && PS1='OR''IGIN_ENV:rkkfQQ2y# ' && PROMPT_COMMAND='sleep .05||sleep 1'
                                                                                  ================================================================================
                                                                                  Sending>>> export PS1_ORIGIN_ENV=$PS1 && PS1='OR''IGIN_ENV:rkkfQQ2y# ' && PROMPT_COMMAND='sleep .05||sleep 1'<<<, expecting>>>['\r\nORIGIN_ENV:rkkfQQ2y# ']<<<
                                                                                  Sending in pexpect session (68242035994000): export PS1_ORIGIN_ENV=$PS1 && PS1='OR''IGIN_ENV:rkkfQQ2y# ' && PROMPT_COMMAND='sleep .05||sleep 1'
                                                                                  Expecting: ['\r\nORIGIN_ENV:rkkfQQ2y# ']
                                                                                  export PS1_ORIGIN_ENV=$PS1 && PS1='OR''IGIN_ENV:rkkfQQ2y# ' && PROMPT_COMMAND='sleep .05||sleep 1'
                                                                                  root@localhost:/myapp# export PS1_ORIGIN_ENV=$PS1 && PS1='OR''IGIN_ENV:rkkfQQ2y# ' && PROMPT_COMMAND='sleep .05||sleep 1'
                                                                                  Stopped sleep .05
                                                                                  Stopped sleep 1
                                                                                  pexpect: buffer: b'' before: b'cm9vdEBsb2NhbGhvc3Q6L3B1YnN1YiMgIGV4cx' after: b'DQpPUklHSU5fRU5WOnJra2ZRUTJ5IyA='
                                                                                  Resetting default expect to: ORIGIN_ENV:rkkfQQ2y# 
                                                                                  In session: host_child, trying to send: stty cols 65535
                                                                                  ================================================================================
                                                                                  Sending>>> stty cols 65535<<<, expecting>>>ORIGIN_ENV:rkkfQQ2y# <<<
                                                                                  Sending in pexpect session (68242035994000): stty cols 65535
                                                                                  Expecting: ORIGIN_ENV:rkkfQQ2y# 
                                                                                  ORIGIN_ENV:rkkfQQ2y# stty cols 65535
                                                                                  stty cols 65535
                                                                                  Stopped stty cols 65535
                                                                                  Stopped sleep .05
                                                                                  Stopped sleep 1
                                                                                  

                                                                                  Workarounds tried:

                                                                                  • Different regions: a few European(tier 1 and 2), Asia, US.
                                                                                  • Build with docker instead of kaniko
                                                                                  • Different CPU and Memory allocated to the container
                                                                                  • Minimum number of containers 1-5 (to ensure CPU is always allocated to the container)
                                                                                  • --no-cpu-throttling also made no difference
                                                                                  • Maximum number of containers 1-30
                                                                                  • Different GCP project
                                                                                  • Different Docker base images (3.5-3.9 + various shas ranging from a year ago to recent ones)

                                                                                  ANSWER

                                                                                  Answered 2021-Sep-23 at 12:35

                                                                                  It's not a perfect replacement but you can use one of the following instead:

                                                                                  I'm not sure what's the big picture so I'll add various options

                                                                                  For remote automation tasks from a flask web server we're using paramiko for its simplicity and quick setup, though you might prefer something like pyinfra for large projects or subprocess for small local tasks.

                                                                                  1. Paramiko - a bit more hands-on\manual than shutit, run commands over the ssh protocol.

                                                                                  example:

                                                                                  import paramiko
                                                                                  
                                                                                  ip='server ip'
                                                                                  port=22
                                                                                  # you can also use ssh keys
                                                                                  username='username'
                                                                                  password='password'
                                                                                  
                                                                                  cmd='some useful command' 
                                                                                  
                                                                                  ssh=paramiko.SSHClient()
                                                                                  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                                                                                  ssh.connect(ip,port,username,password)
                                                                                  
                                                                                  stdin,stdout,stderr=ssh.exec_command(cmd)
                                                                                  outlines=stdout.readlines()
                                                                                  resp=''.join(outlines)
                                                                                  print(resp)
                                                                                  

                                                                                  more examples

                                                                                  1. pyinfra - ansible like library to automate tasks in ad-hoc style

                                                                                  example to install a package using apt:

                                                                                  from pyinfra.operations import apt
                                                                                  
                                                                                  apt.packages(
                                                                                      name='Ensure iftop is installed',
                                                                                      packages=['iftop'],
                                                                                      sudo=True,
                                                                                      update=True,
                                                                                  )
                                                                                  
                                                                                  1. subprocess - like Paramiko not as extensive as shutit but works like a charm

                                                                                  Source https://stackoverflow.com/questions/69265924

                                                                                  QUESTION

                                                                                  Create a database trigger in an event listener
                                                                                  Asked 2021-Sep-22 at 17:53

                                                                                  I have a flask API and I'm using Flask-SQLAlchemy to handle a SQLite database. I have a table which stores log entries, and I want to limit the maximum number of rows to a number n. Since insertions are also made from another script outside of flask using raw SQL, I created a trigger that checks the number of rows and deletes the oldest ones if the number is higher than n:

                                                                                  CREATE TRIGGER 'trigger_log_insert' 
                                                                                  BEFORE INSERT ON 'connection_logs' 
                                                                                  WHEN ( SELECT count(*) FROM  'connection_logs' ) > 5 
                                                                                  BEGIN 
                                                                                  DELETE FROM 'connection_logs' 
                                                                                  WHERE id NOT IN ( SELECT id FROM 'connection_logs' ORDER BY id DESC LIMIT 5 ); 
                                                                                  END
                                                                                  

                                                                                  This trigger works as expected, but I am struggling to set it using flask-sqlalchemy. How can I set the trigger / execute raw SQL using flask-sqlalchemy? The SQL only needs to be executed once after db creation so I intent to execute it right after my create_all() statement. I stumbled upon this StackOverflow answer which suggested a solution that is apparently going to be deprecated soon. I also read the SQLAlchemy documentation about custom DDL, but I don't know how to create this custom DDL with flask_sqlalchemy. When I create the DDL like in the SQLAlchemy documentation, I get an error message saying DDL object is not bound to an Engine or Connection.:

                                                                                  trigger = DDL(
                                                                                  "CREATE TRIGGER 'trigger_log_insert'"
                                                                                  "BEFORE INSERT ON 'connection_logs'"
                                                                                  "WHEN ( SELECT count(*) FROM  'connection_logs' ) > 5"
                                                                                  "BEGIN"
                                                                                  "DELETE FROM 'connection_logs' WHERE id NOT IN"
                                                                                  "("
                                                                                  "SELECT id FROM 'connection_logs' ORDER BY id DESC LIMIT 5"
                                                                                  ");"
                                                                                  "END"
                                                                                  )
                                                                                  
                                                                                  event.listen(ConnectionLog, 'after_create', trigger.execute())
                                                                                  

                                                                                  My model is defined using flask-sqlalchemy's declarative base model:

                                                                                  class ConnectionLog(db.Model):
                                                                                      __tablename__ = 'connection_logs'
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2021-Sep-19 at 17:01

                                                                                  You don't need to create a DDL instance, you can execute the SQL within the listener function. The relevant docs are here.

                                                                                  import sqlalchemy as sa
                                                                                  ...
                                                                                  
                                                                                  class ConnectionLog(db.Model):
                                                                                      __tablename__ = 'connection_logs'
                                                                                  ...
                                                                                  
                                                                                  def after_create(target, connection, **kw):
                                                                                      connection.execute(sa.text("""\
                                                                                          CREATE TRIGGER 'trigger_log_insert'
                                                                                          BEFORE INSERT ON 'connection_logs'
                                                                                          WHEN ( SELECT count(*) FROM  'connection_logs' ) > 5
                                                                                          BEGIN
                                                                                          DELETE FROM 'connection_logs' WHERE id NOT IN
                                                                                          (
                                                                                          SELECT id FROM 'connection_logs' ORDER BY id DESC LIMIT 5
                                                                                          );
                                                                                          END
                                                                                          """
                                                                                      ))
                                                                                  
                                                                                  # Listen on the underlying table object, not on the model class.
                                                                                  sa.event.listen(ConnectionLog.__table__, "after_create", after_create)
                                                                                  

                                                                                  Ensure that the interpreter has read this code before creating the tables.

                                                                                  Source https://stackoverflow.com/questions/68952710

                                                                                  Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                                                                                  Vulnerabilities

                                                                                  No vulnerabilities reported

                                                                                  Install flask

                                                                                  You can install using 'pip install flask' or download it from GitHub, PyPI.
                                                                                  You can use flask like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.

                                                                                  Support

                                                                                  For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .
                                                                                  Find more information at:
                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit
                                                                                  Install
                                                                                • PyPI

                                                                                  pip install Flask

                                                                                • CLONE
                                                                                • HTTPS

                                                                                  https://github.com/pallets/flask.git

                                                                                • CLI

                                                                                  gh repo clone pallets/flask

                                                                                • sshUrl

                                                                                  git@github.com:pallets/flask.git

                                                                                • Share this Page

                                                                                  share link

                                                                                  Explore Related Topics

                                                                                  Consider Popular Web Framework Libraries

                                                                                  angular

                                                                                  by angular

                                                                                  flask

                                                                                  by pallets

                                                                                  gin

                                                                                  by gin-gonic

                                                                                  php-src

                                                                                  by php

                                                                                  symfony

                                                                                  by symfony

                                                                                  Try Top Libraries by pallets

                                                                                  click

                                                                                  by palletsPython

                                                                                  jinja

                                                                                  by palletsPython

                                                                                  werkzeug

                                                                                  by palletsPython

                                                                                  flask-sqlalchemy

                                                                                  by palletsPython

                                                                                  itsdangerous

                                                                                  by palletsPython

                                                                                  Compare Web Framework Libraries with Highest Support

                                                                                  angular

                                                                                  by angular

                                                                                  amphtml

                                                                                  by ampproject

                                                                                  symfony

                                                                                  by symfony

                                                                                  flask

                                                                                  by pallets

                                                                                  gin

                                                                                  by gin-gonic

                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit