#๐Ÿ”’ Connecting SQlite database to flask

54 messages ยท Page 1 of 1 (latest)

rancid cragBOT
#

@viral wharf

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

gusty ingot
#

You should be much more descriptive about where you are at and what immediate problem you are facing, or people won't be very likely to respond to your help thread.

#

Since I helped you before, I know there's more to it than what you've written in your initial message, so I know there's a lot more you could talk about.

viral wharf
#

I donโ€™t fully know what iโ€™m doing so itโ€™s hard to describe

mystic slate
#

Your schema.sql file does not connect directly to the database. Rather, that file contains SQL code describing the schema of your tables and their columns (I'm assuming based on its name, anyway).

You interact with a database using SQL statements, such as the ones you might find in that file.

Flask doesn't have a special method for connecting to the database: you would do that yourself using, in this case, the sqlite3 module built into Python.

#

Perhaps another resource tailored to SQL basics might help, as well.

gusty ingot
viral wharf
gusty ingot
viral wharf
#

schema.sql:

CREATE IF NOT EXISTS league;
CREATE IF NOT EXISTS games;
CREATE IF NOT EXISTS teams;
CREATE IF NOT EXISTS players;

CREATE TABLE league (
    league_id INTEGER PRIMARY KEY AUTOINCREMENT,
    team_id REFERENCES teams (team_id),
    wins INTEGER DEFAULT 0,
    draws INTEGER DEFAULT 0,
    losses INTEGER DEFAULT 0,
    games_played INTEGER DEFAULT 0,
    points INTEGER DEFAULT 0
);

CREATE TABLE games (
    game_id INTEGER PRIMARY KEY AUTOINCREMENT,
    date_time DATE NOT NULL,
    hometeam_id REFERENCES teams (team_id),
    awayteam_id REFERENCES teams (team_id),
    hometeam_singles_score INTEGER NOT NULL,
    awayteam_singles_score INTEGER NOT NULL,
    hometeam_doubles_score INTEGER NOT NULL,
    awayteam_doubles_score INTEGER NOT NULL
);

CREATE TABLE teams (
    team_id INTEGER PRIMARY KEY AUTOINCREMENT,
    teamname VARCHAR(50)
);

CREATE TABLE players (
    player_id INTEGER PRIMARY KEY AUTOINCREMENT,
    team_id REFERENCES teams (team_id),
    playername TEXT NOT NULL
);
#

__init__.py:

import os
from flask import Flask


def create_app(test_config=None):
    # Create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='13a18b15677184599b28e708546b363d500ea19824b098fcaf773e3580cb45ef',
        DATABASE=os.path.join(app.instance_path, 'darts.sqlite'),
    )

    if test_config is None:
        # Load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # Load the test config if passed in
        app.config.from_mapping(test_config)

    # Ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # A simple home page
    @app.route('/home')
    def hello():
        return 'Section B league home page!'
    
    return app
#

those are my two files right now

#

in the darts-league folder

#

okay i need to register the database with the application (flask)

#

and then initalise it

#

i just need someone to help me do that

gusty ingot
#

What about your db file from before?

viral wharf
#

ah yeah i will need to create one of those

#

i now have a db.py file too

gusty ingot
#

You can refer back to the tutorial you went through before, and the blog app you made

#

Compare the code and see what differs

gusty ingot
#

You didn't register the database with flask in the blog either

viral wharf
#

Thats what the subtitle says though?

gusty ingot
#

You registered a CLI command that called a function you wrote which initiated the database, and you registered a function you wrote to be called when the flask app shuts down, which closes the database connection

#

So in neither case does Flask itself know about the database

#

It just knows about some functions that you want to call when certain things happen (like when your run a console command, or when the Flask app closes)

#

And all the database stuff happens inside those functions

viral wharf
#

Oh I see

#

That actually helps me understand the code more

gusty ingot
#

You can also look at your blog code to see how to use the database connection in response to web requests, like when you add a new blog post for example

viral wharf
#

Yeah, im getting an error when running the command

gusty ingot
#

If you want help with an error in general, you should always just copy and paste the error into the chat

#

Because that's always gonna be necessary anyway to help you

viral wharf
#

damn its too long

#
  File "C:\Users\georg\OneDrive\Documents\GitHub\Darts-League-Project\darts-league\__init__.py", line 32, in create_app   
    db.init_app(app)
    ^^^^^^^^^^^
AttributeError: module 'darts-league.db' has no attribute 'init_app'. Did you mean: 'init_db'?
PS C:\Users\georg\OneDrive\Documents\GitHub\Darts-League-Project> 
#

thats the last bit

gusty ingot
#

Well, what does the error message say?

viral wharf
#

It says about darts-league.db but that isnt created anywhere

gusty ingot
#

darts-league is the name of the package, since db.py is in a directory called darts-league, which contains an __init__.py file

viral wharf
#

okay i see

gusty ingot
#

In Python, a module is just a single file that contains Python code โ€” like functions, classes, or variables โ€” that you can use in other programs. A package is a collection of modules grouped together in a folder with a special file called __init__.py, which helps Python recognize it as a package. Think of modules as individual tools, and packages as organized toolboxes full of related tools. They make it easier to keep code organized and reuse it across different projects.

viral wharf
#

i did it!!

#

the db has been initialised

gusty ingot
#

Nice

viral wharf
#

there we go!

#

is the sqlite_sequence meant to be there

gusty ingot
#

Yes, it's created automatically to keep track of AUTOINCREMENT fields

viral wharf
#

Ahh okay I see

#

So, i will move onto the next step of the tutorial and see how i link it into my project

rancid cragBOT
#
Python help channel closed using Discord native close action

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.