kandi background
Explore Kits

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

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

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

Download this library from

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 build file available, it has a Permissive License and it has high support. You can download it from GitHub.
The Python micro framework for building web applications.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • flask has a highly active ecosystem.
  • It has 58462 star(s) with 14977 fork(s). There are 2178 watchers for this library.
  • There were 3 major release(s) in the last 12 months.
  • There are 12 open issues and 2271 have been closed. On average issues are closed in 7 days. There are 1 open pull requests and 0 closed requests.
  • It has a negative sentiment in the developer community.
  • The latest version of flask is 2.1.1
flask Support
Best in #Web Framework
Average in #Web Framework
flask Support
Best in #Web Framework
Average in #Web Framework

quality kandi Quality

  • 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

securitySecurity

  • flask has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • flask code analysis shows 0 unresolved vulnerabilities.
  • 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

license License

  • flask is licensed under the BSD-3-Clause License. This license is Permissive.
  • 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

buildReuse

  • flask releases are available to install and integrate.
  • Build file is available. You can build the component from source.
  • flask saves you 4755 person hours of effort in developing the same functionality from scratch.
  • It has 10184 lines of code, 1378 functions and 96 files.
  • 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.

                                    Python/Docker ImportError: cannot import name 'json' from itsdangerous

                                    copy iconCopydownload iconDownload
                                    pip install Flask=2.0.3
                                    
                                    pip install Flask=2.0.1
                                    
                                    pip install Flask=2.1.0
                                    
                                    pip install Flask==1.1.4
                                    pip install markupsafe==2.0.1
                                    
                                    pip install Flask=2.0.1
                                    
                                    pip install Flask=2.1.0
                                    
                                    pip install Flask==1.1.4
                                    pip install markupsafe==2.0.1
                                    
                                    pip install Flask=2.0.1
                                    
                                    pip install Flask=2.1.0
                                    
                                    pip install Flask==1.1.4
                                    pip install markupsafe==2.0.1
                                    

                                    TypeError: __init__() got an unexpected keyword argument 'as_tuple'

                                    copy iconCopydownload iconDownload
                                    # in requirements.txt
                                    werkzeug==2.0.3
                                    

                                    in VS Code ImportError: cannot import name 'Mapping' from 'collections'

                                    copy iconCopydownload iconDownload
                                    from collections import Mapping
                                    
                                    from collections.abc import Mapping
                                    
                                    from collections import Mapping
                                    
                                    from collections.abc import Mapping
                                    
                                    try:
                                        from collections.abc import Mapping
                                    except ImportError:
                                        from collections import Mapping
                                    

                                    How to set schema_translate_map in SQLAlchemy object in Flask app

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

                                    WebSocket not working when trying to send generated answer by keras

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

                                    localhost:5000 unavailable in macOS v12 (Monterey)

                                    copy iconCopydownload iconDownload
                                    python3 -m http.server 5000
                                    
                                    Serving HTTP on :: port 5000 (http://[::]:5000/) ...
                                    
                                    python3 -m http.server 4999
                                    
                                    export FLASK_APP=hello
                                    flask run -p 4999
                                    
                                    python3 -m http.server 5000
                                    
                                    Serving HTTP on :: port 5000 (http://[::]:5000/) ...
                                    
                                    python3 -m http.server 4999
                                    
                                    export FLASK_APP=hello
                                    flask run -p 4999
                                    
                                    python3 -m http.server 5000
                                    
                                    Serving HTTP on :: port 5000 (http://[::]:5000/) ...
                                    
                                    python3 -m http.server 4999
                                    
                                    export FLASK_APP=hello
                                    flask run -p 4999
                                    

                                    SQLAlchemy - Adding a ForeignKeyConstraint to a many-to-many table that is based on another relationship

                                    copy iconCopydownload iconDownload
                                    # create new image with id = 1 and linked episode = 1
                                    my_image = Image(...) 
                                    
                                    # my personas
                                    Persona.query.all()
                                    [<Persona('Homer')>, <Persona('Marge')>, <Persona('Pikachu')>]
                                    
                                    # my episodes
                                    >>> Episode.query.all()
                                    [<Episode('the simpson')>]
                                    
                                    #my images
                                    >>> Image.query.all()
                                    [<Image 1>, <Image 2>]
                                    
                                    # personas in first image
                                    >>> Image.query.all()[0].personas
                                    [<Persona('Marge')>]
                                    
                                    # which episode?
                                    >>> Image.query.all()[0].episode
                                    <Episode('the simpson')>
                                    
                                    # same as above but with next personas (Note that Pikachu is linked to the wrong episode)
                                    >>> Image.query.all()[1].personas
                                    [<Persona('Pikachu')>]
                                    >>> Image.query.all()[1].episode
                                    <Episode('the simpson')>
                                    
                                    # 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
                                    
                                    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
                                    -- Need relationship as below
                                    );
                                    
                                    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) -- No need as below
                                    );
                                    
                                    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)-- No need as below
                                    );
                                    
                                    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,
                                    clips_id VARCHAR(10) NOT NULL,
                                    clips_id INT NOT NULL ,
                                    images_id INT NOT NULL ,
                                    FOREIGN KEY(clips_id) REFERENCES clips(id)
                                    FOREIGN KEY(images_id) REFERENCES images(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
                                    );
                                    
                                    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
                                    );
                                    
                                    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
                                    -- Need relationship as below
                                    );
                                    
                                    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) -- No need as below
                                    );
                                    
                                    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)-- No need as below
                                    );
                                    
                                    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,
                                    clips_id VARCHAR(10) NOT NULL,
                                    clips_id INT NOT NULL ,
                                    images_id INT NOT NULL ,
                                    FOREIGN KEY(clips_id) REFERENCES clips(id)
                                    FOREIGN KEY(images_id) REFERENCES images(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
                                    );
                                    
                                    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
                                    );
                                    
                                    episode_id_nullable = db.engine.dialect.name == "sqlite"                # Add this
                                    
                                    personas_clips = db.Table(
                                        "personas_clips",
                                        db.Column("persona_id", db.ForeignKey("personas.id"), primary_key=True),
                                        db.Column("episode_id", db.Integer, nullable=episode_id_nullable),  # Add this
                                        db.Column("clip_id", db.ForeignKey("clips.id"), primary_key=True),
                                        db.ForeignKeyConstraint(["persona_id", "episode_id"], ["personas_episodes.persona_id", "personas_episodes.episode_id"]),  # Add this
                                    )
                                    
                                    personas_images = db.Table(
                                        "personas_images",
                                        db.Column("persona_id", db.ForeignKey("personas.id"), primary_key=True),
                                        db.Column("episode_id", db.Integer, nullable=episode_id_nullable),  # Add this
                                        db.Column("image_id", db.ForeignKey("images.id"), primary_key=True),
                                        db.ForeignKeyConstraint(["persona_id", "episode_id"], ["personas_episodes.persona_id", "personas_episodes.episode_id"]),  # Add this
                                    )
                                    
                                    SQLITE_CHECK_EPISODE_ID_BEFORE_INSERT = """
                                    CREATE TRIGGER {table_name}_check_episode_id_before_insert BEFORE INSERT ON {table_name}
                                      FOR EACH ROW
                                      WHEN NEW.episode_id IS NULL
                                      BEGIN
                                        SELECT RAISE(ABORT, 'NOT NULL constraint failed: {table_name}.episode_id') WHERE NOT EXISTS (
                                            SELECT 1
                                            FROM {fk_target_table_name}
                                            JOIN personas_episodes ON {fk_target_table_name}.episode_id = personas_episodes.episode_id
                                            WHERE {fk_target_table_name}.{fk_target_name} = NEW.{fk_name}
                                              AND personas_episodes.persona_id = NEW.persona_id
                                        );
                                      END;
                                    """
                                    
                                    SQLITE_CHECK_EPISODE_ID_BEFORE_UPDATE = """
                                    CREATE TRIGGER {table_name}_check_episode_id_before_update BEFORE UPDATE ON {table_name}
                                      FOR EACH ROW
                                      WHEN NEW.episode_id IS NULL
                                      BEGIN
                                        SELECT RAISE(ABORT, 'NOT NULL constraint failed: {table_name}.episode_id');
                                      END;
                                    """
                                    
                                    SQLITE_AUTOFILL_EPISODE_ID = """
                                    CREATE TRIGGER {table_name}_autofill_episode_id AFTER INSERT ON {table_name}
                                      FOR EACH ROW
                                      WHEN NEW.episode_id IS NULL
                                      BEGIN
                                        UPDATE {table_name}
                                        SET episode_id = (SELECT {fk_target_table_name}.episode_id
                                            FROM {fk_target_table_name}
                                            JOIN personas_episodes ON {fk_target_table_name}.episode_id = personas_episodes.episode_id
                                            WHERE {fk_target_table_name}.{fk_target_name} = NEW.{fk_name}
                                              AND personas_episodes.persona_id = NEW.persona_id)
                                        WHERE {fk_name} = NEW.{fk_name}
                                          AND persona_id = NEW.persona_id;
                                      END;
                                    """
                                    
                                    POSTGRESQL_AUTOFILL_EPISODE_ID = """
                                    CREATE OR REPLACE FUNCTION {table_name}_autofill_episode_id() RETURNS TRIGGER AS ${table_name}_autofill_episode_id$
                                      DECLARE
                                        _episode_id INT;
                                        in_episode BOOL;
                                      BEGIN
                                        IF NEW.episode_id IS NULL THEN
                                            SELECT episode_id INTO _episode_id FROM {fk_target_table_name} WHERE {fk_target_name} = NEW.{fk_name};
                                            SELECT TRUE INTO in_episode FROM personas_episodes WHERE persona_id = NEW.persona_id AND episode_id = _episode_id;
                                            IF in_episode IS NOT NULL THEN
                                                NEW.episode_id = _episode_id;
                                            END IF;
                                        END IF;
                                        RETURN NEW;
                                      END;
                                    ${table_name}_autofill_episode_id$ LANGUAGE plpgsql;
                                    
                                    CREATE TRIGGER {table_name}_autofill_episode_id BEFORE INSERT OR UPDATE ON {table_name}
                                      FOR EACH ROW EXECUTE PROCEDURE {table_name}_autofill_episode_id();
                                    """
                                    
                                    from sqlalchemy import event, text
                                    
                                    
                                    def after_create_trigger_autofill_episode_id(target, connection, **kw):
                                        fk = next(fk for fk in target.foreign_keys if "personas" not in fk.column.table.name)
                                        if connection.dialect.name == "sqlite":
                                            connection.execute(text(SQLITE_CHECK_EPISODE_ID_BEFORE_INSERT.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name,fk_name=fk.parent.name)))
                                            connection.execute(text(SQLITE_CHECK_EPISODE_ID_BEFORE_UPDATE.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name, fk_name=fk.parent.name)))
                                            connection.execute(text(SQLITE_AUTOFILL_EPISODE_ID.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name, fk_name=fk.parent.name)))
                                        elif connection.dialect.name == "postgresql":
                                            connection.execute(text(POSTGRESQL_AUTOFILL_EPISODE_ID.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name, fk_name=fk.parent.name)))
                                    
                                    
                                    event.listen(personas_clips, "after_create", after_create_trigger_autofill_episode_id)
                                    event.listen(personas_images, "after_create", after_create_trigger_autofill_episode_id)
                                    
                                    from sqlalchemy.exc import IntegrityError
                                    from sqlalchemy.sql import select
                                    
                                    from models import *
                                    
                                    if db.engine.dialect.name == "sqlite":
                                        db.session.execute("pragma foreign_keys=on")
                                    else:
                                        db.session.execute("""
                                    DROP TABLE IF EXISTS episodes CASCADE;
                                    DROP TABLE IF EXISTS personas CASCADE;
                                    DROP TABLE IF EXISTS personas_episodes CASCADE;
                                    DROP TABLE IF EXISTS clips CASCADE;
                                    DROP TABLE IF EXISTS personas_clips;
                                    DROP TABLE IF EXISTS images CASCADE;
                                    DROP TABLE IF EXISTS personas_images;
                                    """)
                                        db.session.commit()
                                    
                                    db.create_all()
                                    
                                    e1 = Episode(title="Some Episode")
                                    e2 = Episode(title="Another Episode")
                                    db.session.add(e1)
                                    db.session.add(e2)
                                    db.session.commit()
                                    
                                    p1 = Persona(name="Raider Dave", episodes=[e1])
                                    p2 = Persona(name="Ricky Spanish", episodes=[e2])
                                    db.session.add(p1)
                                    db.session.add(p2)
                                    db.session.commit()
                                    
                                    c1 = Clip(title="A clip", episode=e1, personas=[p2])         # should fail
                                    db.session.add(c1)
                                    try:
                                        db.session.commit()
                                        assert False
                                    except IntegrityError:
                                        db.session.rollback()
                                    assert Clip.query.first() is None, list(db.session.execute(select(personas_clips)))
                                    
                                    i1 = Image(link="An image", episode=e2, personas=[p1])       # should fail
                                    db.session.add(i1)
                                    try:
                                        db.session.commit()
                                        assert False
                                    except IntegrityError:
                                        db.session.rollback()
                                    assert Image.query.first() is None, list(db.session.execute(select(personas_images)))
                                    
                                    c2 = Clip(title="Another clip", episode=e1, personas=[p1])   # should succeed
                                    db.session.add(c2)
                                    db.session.commit()
                                    assert Clip.query.first() is not None
                                    
                                    i2 = Image(link="Another image", episode=e2, personas=[p2])  # should succeed
                                    db.session.add(i2)
                                    db.session.commit()
                                    assert Image.query.first() is not None
                                    
                                    episode_id_nullable = db.engine.dialect.name == "sqlite"                # Add this
                                    
                                    personas_clips = db.Table(
                                        "personas_clips",
                                        db.Column("persona_id", db.ForeignKey("personas.id"), primary_key=True),
                                        db.Column("episode_id", db.Integer, nullable=episode_id_nullable),  # Add this
                                        db.Column("clip_id", db.ForeignKey("clips.id"), primary_key=True),
                                        db.ForeignKeyConstraint(["persona_id", "episode_id"], ["personas_episodes.persona_id", "personas_episodes.episode_id"]),  # Add this
                                    )
                                    
                                    personas_images = db.Table(
                                        "personas_images",
                                        db.Column("persona_id", db.ForeignKey("personas.id"), primary_key=True),
                                        db.Column("episode_id", db.Integer, nullable=episode_id_nullable),  # Add this
                                        db.Column("image_id", db.ForeignKey("images.id"), primary_key=True),
                                        db.ForeignKeyConstraint(["persona_id", "episode_id"], ["personas_episodes.persona_id", "personas_episodes.episode_id"]),  # Add this
                                    )
                                    
                                    SQLITE_CHECK_EPISODE_ID_BEFORE_INSERT = """
                                    CREATE TRIGGER {table_name}_check_episode_id_before_insert BEFORE INSERT ON {table_name}
                                      FOR EACH ROW
                                      WHEN NEW.episode_id IS NULL
                                      BEGIN
                                        SELECT RAISE(ABORT, 'NOT NULL constraint failed: {table_name}.episode_id') WHERE NOT EXISTS (
                                            SELECT 1
                                            FROM {fk_target_table_name}
                                            JOIN personas_episodes ON {fk_target_table_name}.episode_id = personas_episodes.episode_id
                                            WHERE {fk_target_table_name}.{fk_target_name} = NEW.{fk_name}
                                              AND personas_episodes.persona_id = NEW.persona_id
                                        );
                                      END;
                                    """
                                    
                                    SQLITE_CHECK_EPISODE_ID_BEFORE_UPDATE = """
                                    CREATE TRIGGER {table_name}_check_episode_id_before_update BEFORE UPDATE ON {table_name}
                                      FOR EACH ROW
                                      WHEN NEW.episode_id IS NULL
                                      BEGIN
                                        SELECT RAISE(ABORT, 'NOT NULL constraint failed: {table_name}.episode_id');
                                      END;
                                    """
                                    
                                    SQLITE_AUTOFILL_EPISODE_ID = """
                                    CREATE TRIGGER {table_name}_autofill_episode_id AFTER INSERT ON {table_name}
                                      FOR EACH ROW
                                      WHEN NEW.episode_id IS NULL
                                      BEGIN
                                        UPDATE {table_name}
                                        SET episode_id = (SELECT {fk_target_table_name}.episode_id
                                            FROM {fk_target_table_name}
                                            JOIN personas_episodes ON {fk_target_table_name}.episode_id = personas_episodes.episode_id
                                            WHERE {fk_target_table_name}.{fk_target_name} = NEW.{fk_name}
                                              AND personas_episodes.persona_id = NEW.persona_id)
                                        WHERE {fk_name} = NEW.{fk_name}
                                          AND persona_id = NEW.persona_id;
                                      END;
                                    """
                                    
                                    POSTGRESQL_AUTOFILL_EPISODE_ID = """
                                    CREATE OR REPLACE FUNCTION {table_name}_autofill_episode_id() RETURNS TRIGGER AS ${table_name}_autofill_episode_id$
                                      DECLARE
                                        _episode_id INT;
                                        in_episode BOOL;
                                      BEGIN
                                        IF NEW.episode_id IS NULL THEN
                                            SELECT episode_id INTO _episode_id FROM {fk_target_table_name} WHERE {fk_target_name} = NEW.{fk_name};
                                            SELECT TRUE INTO in_episode FROM personas_episodes WHERE persona_id = NEW.persona_id AND episode_id = _episode_id;
                                            IF in_episode IS NOT NULL THEN
                                                NEW.episode_id = _episode_id;
                                            END IF;
                                        END IF;
                                        RETURN NEW;
                                      END;
                                    ${table_name}_autofill_episode_id$ LANGUAGE plpgsql;
                                    
                                    CREATE TRIGGER {table_name}_autofill_episode_id BEFORE INSERT OR UPDATE ON {table_name}
                                      FOR EACH ROW EXECUTE PROCEDURE {table_name}_autofill_episode_id();
                                    """
                                    
                                    from sqlalchemy import event, text
                                    
                                    
                                    def after_create_trigger_autofill_episode_id(target, connection, **kw):
                                        fk = next(fk for fk in target.foreign_keys if "personas" not in fk.column.table.name)
                                        if connection.dialect.name == "sqlite":
                                            connection.execute(text(SQLITE_CHECK_EPISODE_ID_BEFORE_INSERT.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name,fk_name=fk.parent.name)))
                                            connection.execute(text(SQLITE_CHECK_EPISODE_ID_BEFORE_UPDATE.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name, fk_name=fk.parent.name)))
                                            connection.execute(text(SQLITE_AUTOFILL_EPISODE_ID.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name, fk_name=fk.parent.name)))
                                        elif connection.dialect.name == "postgresql":
                                            connection.execute(text(POSTGRESQL_AUTOFILL_EPISODE_ID.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name, fk_name=fk.parent.name)))
                                    
                                    
                                    event.listen(personas_clips, "after_create", after_create_trigger_autofill_episode_id)
                                    event.listen(personas_images, "after_create", after_create_trigger_autofill_episode_id)
                                    
                                    from sqlalchemy.exc import IntegrityError
                                    from sqlalchemy.sql import select
                                    
                                    from models import *
                                    
                                    if db.engine.dialect.name == "sqlite":
                                        db.session.execute("pragma foreign_keys=on")
                                    else:
                                        db.session.execute("""
                                    DROP TABLE IF EXISTS episodes CASCADE;
                                    DROP TABLE IF EXISTS personas CASCADE;
                                    DROP TABLE IF EXISTS personas_episodes CASCADE;
                                    DROP TABLE IF EXISTS clips CASCADE;
                                    DROP TABLE IF EXISTS personas_clips;
                                    DROP TABLE IF EXISTS images CASCADE;
                                    DROP TABLE IF EXISTS personas_images;
                                    """)
                                        db.session.commit()
                                    
                                    db.create_all()
                                    
                                    e1 = Episode(title="Some Episode")
                                    e2 = Episode(title="Another Episode")
                                    db.session.add(e1)
                                    db.session.add(e2)
                                    db.session.commit()
                                    
                                    p1 = Persona(name="Raider Dave", episodes=[e1])
                                    p2 = Persona(name="Ricky Spanish", episodes=[e2])
                                    db.session.add(p1)
                                    db.session.add(p2)
                                    db.session.commit()
                                    
                                    c1 = Clip(title="A clip", episode=e1, personas=[p2])         # should fail
                                    db.session.add(c1)
                                    try:
                                        db.session.commit()
                                        assert False
                                    except IntegrityError:
                                        db.session.rollback()
                                    assert Clip.query.first() is None, list(db.session.execute(select(personas_clips)))
                                    
                                    i1 = Image(link="An image", episode=e2, personas=[p1])       # should fail
                                    db.session.add(i1)
                                    try:
                                        db.session.commit()
                                        assert False
                                    except IntegrityError:
                                        db.session.rollback()
                                    assert Image.query.first() is None, list(db.session.execute(select(personas_images)))
                                    
                                    c2 = Clip(title="Another clip", episode=e1, personas=[p1])   # should succeed
                                    db.session.add(c2)
                                    db.session.commit()
                                    assert Clip.query.first() is not None
                                    
                                    i2 = Image(link="Another image", episode=e2, personas=[p2])  # should succeed
                                    db.session.add(i2)
                                    db.session.commit()
                                    assert Image.query.first() is not None
                                    
                                    episode_id_nullable = db.engine.dialect.name == "sqlite"                # Add this
                                    
                                    personas_clips = db.Table(
                                        "personas_clips",
                                        db.Column("persona_id", db.ForeignKey("personas.id"), primary_key=True),
                                        db.Column("episode_id", db.Integer, nullable=episode_id_nullable),  # Add this
                                        db.Column("clip_id", db.ForeignKey("clips.id"), primary_key=True),
                                        db.ForeignKeyConstraint(["persona_id", "episode_id"], ["personas_episodes.persona_id", "personas_episodes.episode_id"]),  # Add this
                                    )
                                    
                                    personas_images = db.Table(
                                        "personas_images",
                                        db.Column("persona_id", db.ForeignKey("personas.id"), primary_key=True),
                                        db.Column("episode_id", db.Integer, nullable=episode_id_nullable),  # Add this
                                        db.Column("image_id", db.ForeignKey("images.id"), primary_key=True),
                                        db.ForeignKeyConstraint(["persona_id", "episode_id"], ["personas_episodes.persona_id", "personas_episodes.episode_id"]),  # Add this
                                    )
                                    
                                    SQLITE_CHECK_EPISODE_ID_BEFORE_INSERT = """
                                    CREATE TRIGGER {table_name}_check_episode_id_before_insert BEFORE INSERT ON {table_name}
                                      FOR EACH ROW
                                      WHEN NEW.episode_id IS NULL
                                      BEGIN
                                        SELECT RAISE(ABORT, 'NOT NULL constraint failed: {table_name}.episode_id') WHERE NOT EXISTS (
                                            SELECT 1
                                            FROM {fk_target_table_name}
                                            JOIN personas_episodes ON {fk_target_table_name}.episode_id = personas_episodes.episode_id
                                            WHERE {fk_target_table_name}.{fk_target_name} = NEW.{fk_name}
                                              AND personas_episodes.persona_id = NEW.persona_id
                                        );
                                      END;
                                    """
                                    
                                    SQLITE_CHECK_EPISODE_ID_BEFORE_UPDATE = """
                                    CREATE TRIGGER {table_name}_check_episode_id_before_update BEFORE UPDATE ON {table_name}
                                      FOR EACH ROW
                                      WHEN NEW.episode_id IS NULL
                                      BEGIN
                                        SELECT RAISE(ABORT, 'NOT NULL constraint failed: {table_name}.episode_id');
                                      END;
                                    """
                                    
                                    SQLITE_AUTOFILL_EPISODE_ID = """
                                    CREATE TRIGGER {table_name}_autofill_episode_id AFTER INSERT ON {table_name}
                                      FOR EACH ROW
                                      WHEN NEW.episode_id IS NULL
                                      BEGIN
                                        UPDATE {table_name}
                                        SET episode_id = (SELECT {fk_target_table_name}.episode_id
                                            FROM {fk_target_table_name}
                                            JOIN personas_episodes ON {fk_target_table_name}.episode_id = personas_episodes.episode_id
                                            WHERE {fk_target_table_name}.{fk_target_name} = NEW.{fk_name}
                                              AND personas_episodes.persona_id = NEW.persona_id)
                                        WHERE {fk_name} = NEW.{fk_name}
                                          AND persona_id = NEW.persona_id;
                                      END;
                                    """
                                    
                                    POSTGRESQL_AUTOFILL_EPISODE_ID = """
                                    CREATE OR REPLACE FUNCTION {table_name}_autofill_episode_id() RETURNS TRIGGER AS ${table_name}_autofill_episode_id$
                                      DECLARE
                                        _episode_id INT;
                                        in_episode BOOL;
                                      BEGIN
                                        IF NEW.episode_id IS NULL THEN
                                            SELECT episode_id INTO _episode_id FROM {fk_target_table_name} WHERE {fk_target_name} = NEW.{fk_name};
                                            SELECT TRUE INTO in_episode FROM personas_episodes WHERE persona_id = NEW.persona_id AND episode_id = _episode_id;
                                            IF in_episode IS NOT NULL THEN
                                                NEW.episode_id = _episode_id;
                                            END IF;
                                        END IF;
                                        RETURN NEW;
                                      END;
                                    ${table_name}_autofill_episode_id$ LANGUAGE plpgsql;
                                    
                                    CREATE TRIGGER {table_name}_autofill_episode_id BEFORE INSERT OR UPDATE ON {table_name}
                                      FOR EACH ROW EXECUTE PROCEDURE {table_name}_autofill_episode_id();
                                    """
                                    
                                    from sqlalchemy import event, text
                                    
                                    
                                    def after_create_trigger_autofill_episode_id(target, connection, **kw):
                                        fk = next(fk for fk in target.foreign_keys if "personas" not in fk.column.table.name)
                                        if connection.dialect.name == "sqlite":
                                            connection.execute(text(SQLITE_CHECK_EPISODE_ID_BEFORE_INSERT.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name,fk_name=fk.parent.name)))
                                            connection.execute(text(SQLITE_CHECK_EPISODE_ID_BEFORE_UPDATE.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name, fk_name=fk.parent.name)))
                                            connection.execute(text(SQLITE_AUTOFILL_EPISODE_ID.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name, fk_name=fk.parent.name)))
                                        elif connection.dialect.name == "postgresql":
                                            connection.execute(text(POSTGRESQL_AUTOFILL_EPISODE_ID.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name, fk_name=fk.parent.name)))
                                    
                                    
                                    event.listen(personas_clips, "after_create", after_create_trigger_autofill_episode_id)
                                    event.listen(personas_images, "after_create", after_create_trigger_autofill_episode_id)
                                    
                                    from sqlalchemy.exc import IntegrityError
                                    from sqlalchemy.sql import select
                                    
                                    from models import *
                                    
                                    if db.engine.dialect.name == "sqlite":
                                        db.session.execute("pragma foreign_keys=on")
                                    else:
                                        db.session.execute("""
                                    DROP TABLE IF EXISTS episodes CASCADE;
                                    DROP TABLE IF EXISTS personas CASCADE;
                                    DROP TABLE IF EXISTS personas_episodes CASCADE;
                                    DROP TABLE IF EXISTS clips CASCADE;
                                    DROP TABLE IF EXISTS personas_clips;
                                    DROP TABLE IF EXISTS images CASCADE;
                                    DROP TABLE IF EXISTS personas_images;
                                    """)
                                        db.session.commit()
                                    
                                    db.create_all()
                                    
                                    e1 = Episode(title="Some Episode")
                                    e2 = Episode(title="Another Episode")
                                    db.session.add(e1)
                                    db.session.add(e2)
                                    db.session.commit()
                                    
                                    p1 = Persona(name="Raider Dave", episodes=[e1])
                                    p2 = Persona(name="Ricky Spanish", episodes=[e2])
                                    db.session.add(p1)
                                    db.session.add(p2)
                                    db.session.commit()
                                    
                                    c1 = Clip(title="A clip", episode=e1, personas=[p2])         # should fail
                                    db.session.add(c1)
                                    try:
                                        db.session.commit()
                                        assert False
                                    except IntegrityError:
                                        db.session.rollback()
                                    assert Clip.query.first() is None, list(db.session.execute(select(personas_clips)))
                                    
                                    i1 = Image(link="An image", episode=e2, personas=[p1])       # should fail
                                    db.session.add(i1)
                                    try:
                                        db.session.commit()
                                        assert False
                                    except IntegrityError:
                                        db.session.rollback()
                                    assert Image.query.first() is None, list(db.session.execute(select(personas_images)))
                                    
                                    c2 = Clip(title="Another clip", episode=e1, personas=[p1])   # should succeed
                                    db.session.add(c2)
                                    db.session.commit()
                                    assert Clip.query.first() is not None
                                    
                                    i2 = Image(link="Another image", episode=e2, personas=[p2])  # should succeed
                                    db.session.add(i2)
                                    db.session.commit()
                                    assert Image.query.first() is not None
                                    
                                    episode_id_nullable = db.engine.dialect.name == "sqlite"                # Add this
                                    
                                    personas_clips = db.Table(
                                        "personas_clips",
                                        db.Column("persona_id", db.ForeignKey("personas.id"), primary_key=True),
                                        db.Column("episode_id", db.Integer, nullable=episode_id_nullable),  # Add this
                                        db.Column("clip_id", db.ForeignKey("clips.id"), primary_key=True),
                                        db.ForeignKeyConstraint(["persona_id", "episode_id"], ["personas_episodes.persona_id", "personas_episodes.episode_id"]),  # Add this
                                    )
                                    
                                    personas_images = db.Table(
                                        "personas_images",
                                        db.Column("persona_id", db.ForeignKey("personas.id"), primary_key=True),
                                        db.Column("episode_id", db.Integer, nullable=episode_id_nullable),  # Add this
                                        db.Column("image_id", db.ForeignKey("images.id"), primary_key=True),
                                        db.ForeignKeyConstraint(["persona_id", "episode_id"], ["personas_episodes.persona_id", "personas_episodes.episode_id"]),  # Add this
                                    )
                                    
                                    SQLITE_CHECK_EPISODE_ID_BEFORE_INSERT = """
                                    CREATE TRIGGER {table_name}_check_episode_id_before_insert BEFORE INSERT ON {table_name}
                                      FOR EACH ROW
                                      WHEN NEW.episode_id IS NULL
                                      BEGIN
                                        SELECT RAISE(ABORT, 'NOT NULL constraint failed: {table_name}.episode_id') WHERE NOT EXISTS (
                                            SELECT 1
                                            FROM {fk_target_table_name}
                                            JOIN personas_episodes ON {fk_target_table_name}.episode_id = personas_episodes.episode_id
                                            WHERE {fk_target_table_name}.{fk_target_name} = NEW.{fk_name}
                                              AND personas_episodes.persona_id = NEW.persona_id
                                        );
                                      END;
                                    """
                                    
                                    SQLITE_CHECK_EPISODE_ID_BEFORE_UPDATE = """
                                    CREATE TRIGGER {table_name}_check_episode_id_before_update BEFORE UPDATE ON {table_name}
                                      FOR EACH ROW
                                      WHEN NEW.episode_id IS NULL
                                      BEGIN
                                        SELECT RAISE(ABORT, 'NOT NULL constraint failed: {table_name}.episode_id');
                                      END;
                                    """
                                    
                                    SQLITE_AUTOFILL_EPISODE_ID = """
                                    CREATE TRIGGER {table_name}_autofill_episode_id AFTER INSERT ON {table_name}
                                      FOR EACH ROW
                                      WHEN NEW.episode_id IS NULL
                                      BEGIN
                                        UPDATE {table_name}
                                        SET episode_id = (SELECT {fk_target_table_name}.episode_id
                                            FROM {fk_target_table_name}
                                            JOIN personas_episodes ON {fk_target_table_name}.episode_id = personas_episodes.episode_id
                                            WHERE {fk_target_table_name}.{fk_target_name} = NEW.{fk_name}
                                              AND personas_episodes.persona_id = NEW.persona_id)
                                        WHERE {fk_name} = NEW.{fk_name}
                                          AND persona_id = NEW.persona_id;
                                      END;
                                    """
                                    
                                    POSTGRESQL_AUTOFILL_EPISODE_ID = """
                                    CREATE OR REPLACE FUNCTION {table_name}_autofill_episode_id() RETURNS TRIGGER AS ${table_name}_autofill_episode_id$
                                      DECLARE
                                        _episode_id INT;
                                        in_episode BOOL;
                                      BEGIN
                                        IF NEW.episode_id IS NULL THEN
                                            SELECT episode_id INTO _episode_id FROM {fk_target_table_name} WHERE {fk_target_name} = NEW.{fk_name};
                                            SELECT TRUE INTO in_episode FROM personas_episodes WHERE persona_id = NEW.persona_id AND episode_id = _episode_id;
                                            IF in_episode IS NOT NULL THEN
                                                NEW.episode_id = _episode_id;
                                            END IF;
                                        END IF;
                                        RETURN NEW;
                                      END;
                                    ${table_name}_autofill_episode_id$ LANGUAGE plpgsql;
                                    
                                    CREATE TRIGGER {table_name}_autofill_episode_id BEFORE INSERT OR UPDATE ON {table_name}
                                      FOR EACH ROW EXECUTE PROCEDURE {table_name}_autofill_episode_id();
                                    """
                                    
                                    from sqlalchemy import event, text
                                    
                                    
                                    def after_create_trigger_autofill_episode_id(target, connection, **kw):
                                        fk = next(fk for fk in target.foreign_keys if "personas" not in fk.column.table.name)
                                        if connection.dialect.name == "sqlite":
                                            connection.execute(text(SQLITE_CHECK_EPISODE_ID_BEFORE_INSERT.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name,fk_name=fk.parent.name)))
                                            connection.execute(text(SQLITE_CHECK_EPISODE_ID_BEFORE_UPDATE.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name, fk_name=fk.parent.name)))
                                            connection.execute(text(SQLITE_AUTOFILL_EPISODE_ID.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name, fk_name=fk.parent.name)))
                                        elif connection.dialect.name == "postgresql":
                                            connection.execute(text(POSTGRESQL_AUTOFILL_EPISODE_ID.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name, fk_name=fk.parent.name)))
                                    
                                    
                                    event.listen(personas_clips, "after_create", after_create_trigger_autofill_episode_id)
                                    event.listen(personas_images, "after_create", after_create_trigger_autofill_episode_id)
                                    
                                    from sqlalchemy.exc import IntegrityError
                                    from sqlalchemy.sql import select
                                    
                                    from models import *
                                    
                                    if db.engine.dialect.name == "sqlite":
                                        db.session.execute("pragma foreign_keys=on")
                                    else:
                                        db.session.execute("""
                                    DROP TABLE IF EXISTS episodes CASCADE;
                                    DROP TABLE IF EXISTS personas CASCADE;
                                    DROP TABLE IF EXISTS personas_episodes CASCADE;
                                    DROP TABLE IF EXISTS clips CASCADE;
                                    DROP TABLE IF EXISTS personas_clips;
                                    DROP TABLE IF EXISTS images CASCADE;
                                    DROP TABLE IF EXISTS personas_images;
                                    """)
                                        db.session.commit()
                                    
                                    db.create_all()
                                    
                                    e1 = Episode(title="Some Episode")
                                    e2 = Episode(title="Another Episode")
                                    db.session.add(e1)
                                    db.session.add(e2)
                                    db.session.commit()
                                    
                                    p1 = Persona(name="Raider Dave", episodes=[e1])
                                    p2 = Persona(name="Ricky Spanish", episodes=[e2])
                                    db.session.add(p1)
                                    db.session.add(p2)
                                    db.session.commit()
                                    
                                    c1 = Clip(title="A clip", episode=e1, personas=[p2])         # should fail
                                    db.session.add(c1)
                                    try:
                                        db.session.commit()
                                        assert False
                                    except IntegrityError:
                                        db.session.rollback()
                                    assert Clip.query.first() is None, list(db.session.execute(select(personas_clips)))
                                    
                                    i1 = Image(link="An image", episode=e2, personas=[p1])       # should fail
                                    db.session.add(i1)
                                    try:
                                        db.session.commit()
                                        assert False
                                    except IntegrityError:
                                        db.session.rollback()
                                    assert Image.query.first() is None, list(db.session.execute(select(personas_images)))
                                    
                                    c2 = Clip(title="Another clip", episode=e1, personas=[p1])   # should succeed
                                    db.session.add(c2)
                                    db.session.commit()
                                    assert Clip.query.first() is not None
                                    
                                    i2 = Image(link="Another image", episode=e2, personas=[p2])  # should succeed
                                    db.session.add(i2)
                                    db.session.commit()
                                    assert Image.query.first() is not None
                                    
                                    episode_id_nullable = db.engine.dialect.name == "sqlite"                # Add this
                                    
                                    personas_clips = db.Table(
                                        "personas_clips",
                                        db.Column("persona_id", db.ForeignKey("personas.id"), primary_key=True),
                                        db.Column("episode_id", db.Integer, nullable=episode_id_nullable),  # Add this
                                        db.Column("clip_id", db.ForeignKey("clips.id"), primary_key=True),
                                        db.ForeignKeyConstraint(["persona_id", "episode_id"], ["personas_episodes.persona_id", "personas_episodes.episode_id"]),  # Add this
                                    )
                                    
                                    personas_images = db.Table(
                                        "personas_images",
                                        db.Column("persona_id", db.ForeignKey("personas.id"), primary_key=True),
                                        db.Column("episode_id", db.Integer, nullable=episode_id_nullable),  # Add this
                                        db.Column("image_id", db.ForeignKey("images.id"), primary_key=True),
                                        db.ForeignKeyConstraint(["persona_id", "episode_id"], ["personas_episodes.persona_id", "personas_episodes.episode_id"]),  # Add this
                                    )
                                    
                                    SQLITE_CHECK_EPISODE_ID_BEFORE_INSERT = """
                                    CREATE TRIGGER {table_name}_check_episode_id_before_insert BEFORE INSERT ON {table_name}
                                      FOR EACH ROW
                                      WHEN NEW.episode_id IS NULL
                                      BEGIN
                                        SELECT RAISE(ABORT, 'NOT NULL constraint failed: {table_name}.episode_id') WHERE NOT EXISTS (
                                            SELECT 1
                                            FROM {fk_target_table_name}
                                            JOIN personas_episodes ON {fk_target_table_name}.episode_id = personas_episodes.episode_id
                                            WHERE {fk_target_table_name}.{fk_target_name} = NEW.{fk_name}
                                              AND personas_episodes.persona_id = NEW.persona_id
                                        );
                                      END;
                                    """
                                    
                                    SQLITE_CHECK_EPISODE_ID_BEFORE_UPDATE = """
                                    CREATE TRIGGER {table_name}_check_episode_id_before_update BEFORE UPDATE ON {table_name}
                                      FOR EACH ROW
                                      WHEN NEW.episode_id IS NULL
                                      BEGIN
                                        SELECT RAISE(ABORT, 'NOT NULL constraint failed: {table_name}.episode_id');
                                      END;
                                    """
                                    
                                    SQLITE_AUTOFILL_EPISODE_ID = """
                                    CREATE TRIGGER {table_name}_autofill_episode_id AFTER INSERT ON {table_name}
                                      FOR EACH ROW
                                      WHEN NEW.episode_id IS NULL
                                      BEGIN
                                        UPDATE {table_name}
                                        SET episode_id = (SELECT {fk_target_table_name}.episode_id
                                            FROM {fk_target_table_name}
                                            JOIN personas_episodes ON {fk_target_table_name}.episode_id = personas_episodes.episode_id
                                            WHERE {fk_target_table_name}.{fk_target_name} = NEW.{fk_name}
                                              AND personas_episodes.persona_id = NEW.persona_id)
                                        WHERE {fk_name} = NEW.{fk_name}
                                          AND persona_id = NEW.persona_id;
                                      END;
                                    """
                                    
                                    POSTGRESQL_AUTOFILL_EPISODE_ID = """
                                    CREATE OR REPLACE FUNCTION {table_name}_autofill_episode_id() RETURNS TRIGGER AS ${table_name}_autofill_episode_id$
                                      DECLARE
                                        _episode_id INT;
                                        in_episode BOOL;
                                      BEGIN
                                        IF NEW.episode_id IS NULL THEN
                                            SELECT episode_id INTO _episode_id FROM {fk_target_table_name} WHERE {fk_target_name} = NEW.{fk_name};
                                            SELECT TRUE INTO in_episode FROM personas_episodes WHERE persona_id = NEW.persona_id AND episode_id = _episode_id;
                                            IF in_episode IS NOT NULL THEN
                                                NEW.episode_id = _episode_id;
                                            END IF;
                                        END IF;
                                        RETURN NEW;
                                      END;
                                    ${table_name}_autofill_episode_id$ LANGUAGE plpgsql;
                                    
                                    CREATE TRIGGER {table_name}_autofill_episode_id BEFORE INSERT OR UPDATE ON {table_name}
                                      FOR EACH ROW EXECUTE PROCEDURE {table_name}_autofill_episode_id();
                                    """
                                    
                                    from sqlalchemy import event, text
                                    
                                    
                                    def after_create_trigger_autofill_episode_id(target, connection, **kw):
                                        fk = next(fk for fk in target.foreign_keys if "personas" not in fk.column.table.name)
                                        if connection.dialect.name == "sqlite":
                                            connection.execute(text(SQLITE_CHECK_EPISODE_ID_BEFORE_INSERT.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name,fk_name=fk.parent.name)))
                                            connection.execute(text(SQLITE_CHECK_EPISODE_ID_BEFORE_UPDATE.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name, fk_name=fk.parent.name)))
                                            connection.execute(text(SQLITE_AUTOFILL_EPISODE_ID.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name, fk_name=fk.parent.name)))
                                        elif connection.dialect.name == "postgresql":
                                            connection.execute(text(POSTGRESQL_AUTOFILL_EPISODE_ID.format(table_name=target.name, fk_target_table_name=fk.column.table.name, fk_target_name=fk.column.name, fk_name=fk.parent.name)))
                                    
                                    
                                    event.listen(personas_clips, "after_create", after_create_trigger_autofill_episode_id)
                                    event.listen(personas_images, "after_create", after_create_trigger_autofill_episode_id)
                                    
                                    from sqlalchemy.exc import IntegrityError
                                    from sqlalchemy.sql import select
                                    
                                    from models import *
                                    
                                    if db.engine.dialect.name == "sqlite":
                                        db.session.execute("pragma foreign_keys=on")
                                    else:
                                        db.session.execute("""
                                    DROP TABLE IF EXISTS episodes CASCADE;
                                    DROP TABLE IF EXISTS personas CASCADE;
                                    DROP TABLE IF EXISTS personas_episodes CASCADE;
                                    DROP TABLE IF EXISTS clips CASCADE;
                                    DROP TABLE IF EXISTS personas_clips;
                                    DROP TABLE IF EXISTS images CASCADE;
                                    DROP TABLE IF EXISTS personas_images;
                                    """)
                                        db.session.commit()
                                    
                                    db.create_all()
                                    
                                    e1 = Episode(title="Some Episode")
                                    e2 = Episode(title="Another Episode")
                                    db.session.add(e1)
                                    db.session.add(e2)
                                    db.session.commit()
                                    
                                    p1 = Persona(name="Raider Dave", episodes=[e1])
                                    p2 = Persona(name="Ricky Spanish", episodes=[e2])
                                    db.session.add(p1)
                                    db.session.add(p2)
                                    db.session.commit()
                                    
                                    c1 = Clip(title="A clip", episode=e1, personas=[p2])         # should fail
                                    db.session.add(c1)
                                    try:
                                        db.session.commit()
                                        assert False
                                    except IntegrityError:
                                        db.session.rollback()
                                    assert Clip.query.first() is None, list(db.session.execute(select(personas_clips)))
                                    
                                    i1 = Image(link="An image", episode=e2, personas=[p1])       # should fail
                                    db.session.add(i1)
                                    try:
                                        db.session.commit()
                                        assert False
                                    except IntegrityError:
                                        db.session.rollback()
                                    assert Image.query.first() is None, list(db.session.execute(select(personas_images)))
                                    
                                    c2 = Clip(title="Another clip", episode=e1, personas=[p1])   # should succeed
                                    db.session.add(c2)
                                    db.session.commit()
                                    assert Clip.query.first() is not None
                                    
                                    i2 = Image(link="Another image", episode=e2, personas=[p2])  # should succeed
                                    db.session.add(i2)
                                    db.session.commit()
                                    assert Image.query.first() is not None
                                    

                                    Cloud Run Flask API container running shutit enters a sleep loop

                                    copy iconCopydownload iconDownload
                                    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)
                                    
                                    from pyinfra.operations import apt
                                    
                                    apt.packages(
                                        name='Ensure iftop is installed',
                                        packages=['iftop'],
                                        sudo=True,
                                        update=True,
                                    )
                                    
                                    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)
                                    
                                    from pyinfra.operations import apt
                                    
                                    apt.packages(
                                        name='Ensure iftop is installed',
                                        packages=['iftop'],
                                        sudo=True,
                                        update=True,
                                    )
                                    
                                    resource.type="cloud_run_revision"
                                    logName="projects/PROJECT_ID/logs/run.googleapis.com%2Fvarlog%2Fsystem"
                                    

                                    Create a database trigger in an event listener

                                    copy iconCopydownload iconDownload
                                    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)
                                    

                                    Docker-compose error -- panic: runtime error: index out of range [1] with length 1

                                    copy iconCopydownload iconDownload
                                    docker-compose up --remove-orphans // not sure if this step is necessary
                                    docker-compose down
                                    docker-compose up
                                    

                                    Community Discussions

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

                                    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 <module>
                                    veganetworkscript-backend-1  |     from flask import Flask
                                    veganetworkscript-backend-1  |   File "/usr/local/lib/python3.9/site-packages/flask/__init__.py", line 19, in <module>
                                    veganetworkscript-backend-1  |     from . import json
                                    veganetworkscript-backend-1  |   File "/usr/local/lib/python3.9/site-packages/flask/json/__init__.py", line 15, in <module>
                                    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

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

                                    Vulnerabilities

                                    No vulnerabilities reported

                                    Install flask

                                    You can download it from GitHub.
                                    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 .

                                    DOWNLOAD this Library from

                                    Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                                    over 430 million Knowledge Items
                                    Find more libraries
                                    Reuse Solution Kits and Libraries Curated by Popular Use Cases
                                    Explore Kits

                                    Save this library and start creating your kit

                                    Explore Related Topics

                                    Share this Page

                                    share link
                                    Consider Popular Web Framework Libraries
                                    Try Top Libraries by pallets
                                    Compare Web Framework Libraries with Highest Support
                                    Compare Web Framework Libraries with Highest Quality
                                    Compare Web Framework Libraries with Highest Security
                                    Compare Web Framework Libraries with Permissive License
                                    Compare Web Framework Libraries with Highest Reuse
                                    Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                                    over 430 million Knowledge Items
                                    Find more libraries
                                    Reuse Solution Kits and Libraries Curated by Popular Use Cases
                                    Explore Kits

                                    Save this library and start creating your kit

                                    • © 2022 Open Weaver Inc.