What is the best way to set up a peewee SQLite database on the fly?

Currently, I am using the peewee library to work with my sqlite database. Within a module, I have defined various database models as per the examples provided in the documentation. The initialization of the database is outlined in the initial code snippet:

db_model.py

import datetime
from peewee import *

db = SqliteDatabase('my_app.db')

class BaseModel(Model):
    class Meta:
        database = db

class User(BaseModel):
    username = CharField(unique=True)

class Tweet(BaseModel):
    user = ForeignKeyField(User, backref='tweets')
    message = TextField()
    created_date = DateTimeField(default=datetime.datetime.now)
    is_published = BooleanField(default=True)

From what I understand, the database gets initialized at the time the module is imported. Is there a way to initialize the database dynamically during runtime? Any suggestions on how this can be achieved?

Answer №1

Check out the documentation. The section on "Run-time database configuration" might be useful for you:

For example, start the db object with a value of None:

db = SqliteDatabase(None)

... and later in your application:

db.init(<actual parameters>)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Running multiple processes simultaneously is not supported on Windows when using Jupyter Notebook

Currently, I'm running into issues with multiprocessing on Windows using Jupyter notebook. Instead of running all my async's in parallel, they are being executed serially one at a time. Can someone offer guidance on what might be going wrong? I n ...

Tips for waiting for a button to be clicked by the user in Selenium web-driver with Python?

I have a Login form with a username, password, captcha text field, and SIGN-IN button. The elements are clickable and visible from the beginning. https://i.stack.imgur.com/rHbms.png With Selenium, I am able to provide input for the username and password ...

what is the process of naming a variable after the module in a python function

My dilemma involves working with a series of modules and the challenge of calling one within a function based on an argument provided to that function. I attempted a solution, but unfortunately, it did not yield the desired results: from my.set import mod ...

Python Selenium - Unusual Behavior Detected on Website

I have encountered a new issue while trying to scrape tables from a website. When using Selenium, instead of getting the tables displayed in Chrome browser, I am redirected to a login page. This behavior started this week, as my code was working fine until ...

Python SocketTypeError: troubleshooting socket issues

import socket, sys, string if len(sys.argv) !=4: print ("Please provide the server, port, and channel as arguments: ./ninjabot.py <server> <port> <channel>") sys.exit(1) irc = sys.argv[1] port = int(sys.argv[2]) chan = sys.argv ...

I'm feeling a bit lost when it comes to understanding the rebuild/update_index process in Django-H

After deleting a record from my Django app, I initially ran the update_index command followed by the rebuild_index command. The record was still searchable after the first step, but appeared to be gone after the second step when I checked my app. Panicked, ...

Where are cplex solutions typically saved by default?

While running cplex/pyomo, the solver was able to find a solution and reported that it was saved somewhere. Unfortunately, I closed the program before noting down where it was stored. I have searched online but couldn't find any information on its loc ...

Running Selenium scripts in large quantities using Python may encounter obstacles

Greetings, I am currently utilizing selenium to automate the calculation of specific parameters for a bioinformatic project. Everything was going smoothly until I decided to run all the lines together... that's when it stopped working. The code is bei ...

Is there a way for me to locate a non-NaN value within a row?

Every year, I keep track of the prices for four different types of apples. However, there are times when I don't have data for certain years. I'm interested in finding out the unit price for the first year where all apple prices were recorded. ...

The calculation of the total of even and odd numbers incorporates numbers that fall outside of the specified range, regardless of whether they are not

So this is my first semester studying computer science and I'm currently diving into Python. My task was to create a program that calculates the sum of both odd and even numbers between two integers of my choice. It's almost there, but it seems t ...

Python code unexpectedly producing additional newlines

Wondering why these unexpected new lines are appearing while running a simple script. The main goal of the script is to read a file and print each line's content. Here is the code: #!/usr/bin/python import sys # The purpose of this script is to ite ...

Exploring nested JSON or dictionary to find multiple key values that match the defined keys

I'm grappling with a Python object that has multiple layers of dictionaries and lists, each containing keys from which I need to extract values. I stumbled upon an interesting solution involving recursive generators that allows me to fetch the value o ...

Straightforward SQLAlchemy hierarchical inheritance scheme

Presently, I am developing a basic hierarchical database structure. The layout of my model is as follows: class ChatMessage(Base): __tablename__ = 'chat_message' sender_id = Column(Integer, ForeignKey('user.id'), primary_key=Tr ...

When attempting to sign a SOAP message with the zeep package using the PEM format of a JKS key, an error is thrown: zeep.exceptions.Sign

Struggling with signing a SOAP request using a .JKS key in Python, I had to convert the format to .PEM and utilize zeep for sending the request: signature = Signature('client.key.pem', 'client.crt.pem') self.client = Client( ...

Exploring the connections between classes within Django models

My Django Rest Framework project is a blog app that allows logged in users to post text and for any logged in user to add comments to those posts. What changes do I need to make in the Post and Comment classes to establish this logic? from django.db impo ...

Scaling the dimensions of an image for rotation while considering non-square pixels

I am currently working on a Python GUI project using the Kivy framework. In my GUI, I have implemented a windrose feature where an arrow rotates around a circular design to indicate wind direction. The windrose appears circular visually, but due to the scr ...

What could be causing my websocket coroutine to not execute in this particular code?

While utilizing alpaca-py, the new python package from Alpaca, I am developing a basic tradebot. The objective is to have the bot initiate a trade (buy), receive data from Alpaca’s webhook regarding the order fulfillment (along with other details), and t ...

Measuring data significance using Pandas

My Pandas dataframe looks like this: name domain rank1 rank2 rank3 ... rank_mean foo foo.com 1 1 2 ... 1.34 boo boo.it 5 12 ... 6.4 test test.eu 2 2 ... 2.6 The column ...

Python's absence has been noted, thus rendering the script unable to be executed

Today, I encountered an issue while trying to run a Python script: python ./helloworld.py -bash: python: command not found Despite having Python installed on my computer: whereis python python: /usr/bin/python3.6 /usr/bin/python3.6m /usr/lib/python3.6 / ...

Is it possible to execute a particular file for multiprocessing?

Is it feasible to initiate a fresh python process specifically aimed at executing a particular file or module rather than a function present in the current file? The objective would be to: decrease application complexity by segregating the child process ...