def db(): test_db = PostgresqlDatabase('slurpertest') for model in MODELS: model.bind(test_db, bind_refs=False, bind_backrefs=False) test_db.create_tables(MODELS) with test_db.transaction() as txn: yield txn txn.rollback()
async def handle_request(request): global psql_db psql_db = PostgresqlDatabase(database='assp', host='localhost', user='******', password='') psql_db.connect() # Create tables. try: psql_db.create_tables([User]) except OperationalError as e: print(e)
def reset_db(): import os, psycopg2, urllib.parse as urlparse # CHECK urlparse.uses_netloc.append('postgres') url = urlparse.urlparse(os.environ["DATABASE_URL"]) db = PostgresqlDatabase(database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port) db.connect(True) print('CONNECTED') db.drop_tables([AdminPage, TargetGroup, UserPage, SenderPage]) db.create_tables([AdminPage, TargetGroup, UserPage, SenderPage]) return 'DB is reseted!'
async def handle_request(request): global psql_db psql_db = PostgresqlDatabase( database='assp', host='localhost', user='******', password='' ) psql_db.connect() # Create tables. try: psql_db.create_tables([User]) except OperationalError as e: print(e)
class Database: def __init__(self, databaseName, user, password, host, port): self.database = PostgresqlDatabase(databaseName, user=user, password=password, host=host, port=port) def getDatabase(self): return self.database def establishConnection(self): self.database.connect() def closeConnetion(self): self.database.close() def createTables(self, arrOfTables): with self.database: print(self.database) self.database.create_tables(arrOfTables)
db.connect() class BaseModel(Model): class Meta: database = db class Bookmark(BaseModel): name = CharField() category = CharField() url = CharField() # db.drop_tables([Bookmark]) db.create_tables([Bookmark]) def bookmarker(): current_bookmarks() print("What would you like to do?") print("1. Create Bookmark") print("2. Edit Bookmark") print("3. Delete Bookmark") print("4. Get Bookmark details") print("5. Exit") user_answer = int(input("Your selection: ")) if user_answer == 1: create_bookmark() elif user_answer == 2:
db.connect() # Base class BaseModel(Model): class Meta: database = db # Person Model class People(BaseModel): first_name = CharField() number = CharField() db.create_tables([People], safe=True) # People(first_name='Malcolm', number='555-777-3333').save() def prompts_ask(): selection = int(input("Return to the main menu? 1 = Yes or 2 = No: ")) if selection == 1: prompts() elif selection == 2: print("Goodbye") else: prompts_ask() def prompts():
import os from peewee import PostgresqlDatabase database = PostgresqlDatabase(os.environ['munin_db_name'], user=os.environ['munin_db_user'], password=os.environ['munin_db_password'], host=os.environ['munin_db_host']) from munin.models.model import Model from munin.models.user import User from munin.models.token import Token from munin.models.location import Location database.create_tables([User, Token, Location], safe=True)
def init_db_command(): database = PostgresqlDatabase(DATABASE_NAME, **get_db()) database.create_tables([Poll, Choice, VoteCast]) click.echo("Initialized the database.")
else: DB = SqliteDatabase('predictions.db') class Prediction(Model): observation_id = IntegerField(unique=True) observation = TextField() proba = FloatField() true_class = IntegerField(null=True) class Meta: database = DB #DB.drop_tables([Prediction], safe=True) DB.create_tables([Prediction], safe=True) # End database stuff ######################################## ######################################## # Unpickle the previously-trained model with open('columns.json') as fh: columns = json.load(fh) pipeline = joblib.load('pipeline.pickle') with open('dtypes.pickle', 'rb') as fh: dtypes = pickle.load(fh)
from peewee import CharField, DateTimeField, PostgresqlDatabase, Model import datetime from sanic import Sanic from sanic_crud import generate_crud db = PostgresqlDatabase('db', user='******', password='******', host='localhost') class BaseModel(Model): class Meta: database = db class Person(BaseModel): name = CharField() email = CharField() create_datetime = DateTimeField(default=datetime.datetime.now) db.create_tables([Person]) app = Sanic(__name__) generate_crud(app, [Person]) app.run(host="0.0.0.0", port=8000, debug=True)
from peewee import (CharField, Model, PostgresqlDatabase) pg_db = PostgresqlDatabase('movies', user='******', password='******', host='0.0.0.0', port=5444) class UserAccount(Model): name = CharField() class Meta: database = pg_db class Complex(Model): name = CharField() class Meta: database = pg_db pg_db.connect() pg_db.create_tables([UserAccount]) pg_db.create_tables([Complex]) pg_db.commit()
import os from dotenv import load_dotenv from peewee import PostgresqlDatabase from models.Oglas import Zupanija, Grad, Naselje, Oglas load_dotenv() env = os.environ db = PostgresqlDatabase( "nadimistan", user=env.get("DB_USER"), password=env.get("DB_USER_PWD"), host=env.get("DB_HOST"), ) db.create_tables([Zupanija, Grad, Naselje, Oglas])
event = ForeignKeyField(Event, backref='tickets', on_delete='CASCADE') price = DecimalField() total = IntegerField() class Meta: database = db class Order(Model): cellphone = CharField() ticket = ForeignKeyField(Ticket, backref='orders', on_delete='CASCADE') total = IntegerField() class Meta: database = db if __name__ == '__main__': db.create_tables([Promoter, Event, Ticket, Order, ]) from services.promoter import create_promoter from werkzeug.security import generate_password_hash create_promoter(name='Dássone J. Yotamo', email='*****@*****.**', bio='A nice guy online.', password=generate_password_hash('admin'))
def init_db_command(): database = PostgresqlDatabase('payment', **get_db()) database.create_tables([Products, Order]) click.echo("Initialized the database.")
class AssignedTask(Model): user_id= TextField() dwa = TextField() dwa_id = TextField() industry = IntegerField() job = TextField() created_date = DateTimeField(default=datetime.datetime.now) verified_complete = BooleanField(default=False) class Meta: database = DB DB.create_tables([AssignedTask], safe=True) ##safe: If set to True, the create table query will include an IF NOT EXISTS clause. ####End database stuff ######################################## ######################################## # Normal flask app stuff app = Flask(__name__) #use the route() decorator to tell Flask what URL should trigger our function @app.route('/', methods=['POST'])
port=config.DB_PORT) from App.Models.Users import User from App.Models.Quizes import Quiz from App.Models.QuestionText import QuestionText from App.Models.QuestionAnswer import QuestionAnswer # from App.Models.Question import Question # db.drop_tables( # [Quiz, # User, # QuestionText, # QuestionAnswer], # safe = True) db.create_tables([User, Quiz, QuestionText, QuestionAnswer], safe=True) ################ Routes ##################################### from App.control.User import user App.register_blueprint(user) from App.control.Quiz import quiz App.register_blueprint(quiz) from App.control.QuestionText import questiontext App.register_blueprint(questiontext) from App.control.QuestionAnswer import questionanswer App.register_blueprint(questionanswer)
class DatabaseConfig: """ Instances of this class manage the configuration of tha database for the project. This includes the engine, host, port, username, password and database name. The typical work flow using this class is the following: A new object is created from a config dict. Then the database is init-ed (meaning the object is created) Then the database proxy (placeholder) for the models is connected to this database object at run time and then the database is actually connected to its persistent counterpiece (file for sqlite, server for mysql): EXAMPLE: database_config = DatabaseConfig.from_dict(database_dict) database_config.init() database_proxy.initialize(database_config.get()) database_config.connect() database_config.create_tables() # OPTIONAL CHANGELOG Added 09.06.2019 """ # This dict will be used as the default base dict, when a new DatabaseConfig object is to be created from a dict, # which may not contain all the keys. For the keys that are not present, the default ones will stay, but will # otherwise be overwritten. DEFAULT_DICT = { 'engine': 'sqlite', 'host': ':memory:', 'database': '', 'user': '', 'password': '', 'port': 0 } # A list of all valid engine strings SUPPORTED_ENGINES = ['sqlite', 'mysql', 'postgres'] # This is a list, that contains all the model classes of this project. This list is needed to be passed # to the database to create all the tables MODELS = [User, Reward, Pack] # INSTANCE CONSTRUCTION # --------------------- def __init__(self, engine: str, host: str, database: str, user: str, password: str, port: int) -> NoReturn: # This will raise an error, if the engine string is not a valid one self.check_engine(engine) self.engine = engine self.host = host self.database = database self.user = user self.password = password self.port = port # Later on this variable will contain the actual database instance self.instance = None def check_engine(self, engine: str): """ This will raise a value error if the engine string is not one of the supported engines. CHANGELOG Added 09.06.2019 :param engine: :return: """ if engine not in self.SUPPORTED_ENGINES: raise ValueError('The engine "{}" is not supported'.format(engine)) # CREATING DATABASE INSTANCE # -------------------------- def init(self): """ This method will create a new database object and put it into the "self.instance" variable. The type of database object created depends on the value of the engine string CHANGELOG Added 09.06.2019 :return: """ # Basically I am using this dict as a "switch" statement to reduce "if"-clutter engine_create_methods = { 'sqlite': self.init_sqlite, 'mysql': self.init_mysql, 'postgres': self.init_postgres } engine_create_methods[self.engine]() def init_sqlite(self): """ Creates a new sqlite database object and puts it into "self.instance" NOTE: For the creation of a sqlite database only the path to the file is relevant. The "self.host" variable will be used as the sqlite string CHANGELOG Added 09.06.2019 :return: """ self.instance = SqliteDatabase(self.host) def init_mysql(self): """ Creates a new mysql database object and puts it into the "self.instance". CHANGELOG Added 09.06.2019 :return: """ self.instance = MySQLDatabase(self.database, host=self.host, user=self.user, password=self.password, port=self.port) def init_postgres(self): """ Creates a new postgrsql database object and puts it into the "self.instance" CHANGELOG Added 09.06.2019 :return: """ self.instance = PostgresqlDatabase(self.database, host=self.host, user=self.user, password=self.password, port=self.port) # DATABASE OPERATIONS # ------------------- def connect(self): """ When a database object has already been created, this method actually connects the object in "self.instance" to the actual persistent database. CHANGELOG Added 09.06.2019 :return: """ self.instance.connect() def create_tables(self): """ If the database object is already connected and created, this method will create the tables for all the models of the rewardify project into this database. CHANGELOG Added 09.06.2019 :return: """ self.instance.create_tables(self.MODELS) def drop_tables(self): """ If the database object is already connected and created, this method will drop the tables for all the models of the rewardify project into this database. CHANGELOG Added 09.06.2019 :return: """ self.instance.drop_tables(self.MODELS) def get(self): """ returns the database object CHANGELOG Added 09.06.2019 :return: """ return self.instance # UTILITY METHODS # --------------- def update(self, database_dict: Dict) -> NoReturn: """ Given a database dict, all the internal values will be updated according to this dict CHANGELOG Added 09.06.2019 :param database_dict: :return: """ for key, value in database_dict.items(): setattr(self, key, value) # CLASS METHODS # ------------- @classmethod def from_dict(cls, database_dict): """ Given a dict, which contains the database config, this method will create and return a new DatabaseConfig object from it. The dict can contain any subset of the following keys, every key not used it substituted with the default item: - engine - host - database - port - user - password CHANGELOG Added 09.06.2019 :param database_dict: :return: """ # We will use the default dict as a base line (in case not all keys are provided by the given dict as for the # case of sqlite. Then we replace all possible values with the actual ones argument_dict = cls.DEFAULT_DICT argument_dict.update(database_dict) # Finally we can pass the arguments to the constructor by unpacking the dict return cls(**argument_dict)
database = DB table_name = 'dwabadcounts_ml' class DwaEvalCounts_ml(Model): dwatitle = TextField() alreadyevalcount = IntegerField() remainingneedcount = IntegerField() class Meta: database = DB table_name = 'dwaevalcounts_ml' DB.create_tables( [AssignedTask, DwaBadCounts_ml, DwaEvalCounts_ml], safe=True ) ##safe: If set to True, the create table query will include an IF NOT EXISTS clause. ####End database stuff ######################################## ######################################## # Normal flask app stuff app = Flask(__name__) #use the route() decorator to tell Flask what URL should trigger our function @app.route('/', methods=['POST']) def homepage(): return jsonify({'message': 'This is my homepage'})
str_date = CharField() year = IntegerField() month = IntegerField() day = IntegerField() epoch = BigIntegerField() low = FloatField() high = FloatField() open = FloatField() close = FloatField() class Credit(BaseModel) : stock = ForeignKeyField(Stock) client = ForeignKeyField(Client) amount = FloatField() count = IntegerField() date = DateTimeField() debt = FloatField() class StockAssociation(BaseModel) : class Meta: db_table = 'stock_association' stock = ForeignKeyField(Stock) client = ForeignKeyField(Client) count = IntegerField() db.connect() db.create_tables([Client, Stock, History, Credit, StockAssociation, Transaction])
ray.init(redis_address=redis_addr) config = config.LunarLander() config.experience_threads = 1 config.num_epochs = 10 config.episode_batch_size = 40 steps = 0 db = PostgresqlDatabase('testpython', user='******', password='******', host='localhost', port=5432) database_proxy.initialize(db) db.create_tables([PolicyStore]) timings = TimingReport() total_time = util.SimpleInstrument() total_time.start() main() total_time.end() total_time_report = util.SimpleReport() total_time_report.append(total_time) print( f'local {local_mode} threads {config.experience_threads} epochs {config.num_epochs} episodes {config.episode_batch_size} steps {steps}' )
last_zone = IntegerField(default=0) last_instance = IntegerField(default=0) last_clone = BigIntegerField(default=0) last_login = DateTimeField(default=datetime.now) class Inventory(BaseModel): object_id = BigIntegerField() lot = SmallIntegerField() character = ForeignKeyField(Character, backref='items') bound = BooleanField(default=False) amount = SmallIntegerField(default=1) slot = SmallIntegerField() db.create_tables([User, Character, Inventory]) class Database: @staticmethod def create_user(username: str, password: str) -> User: user = User(username=username, password=bcrypt.hashpw(password.encode('latin1'), bcrypt.gensalt()).decode('latin1')) user.save() return user @staticmethod def get_user(user_id: int) -> Optional[User]:
class Meta: table_name = 'movies_category' class MoviesCompany(BaseModel): company_id = ForeignKeyField(Companies) movie_id = ForeignKeyField(Movies) class Meta: table_name = 'movies_company' class Reviews(BaseModel): review = TextField() score = IntegerField() user_id = ForeignKeyField(Users) movie_id = ForeignKeyField(Movies) class Meta: table_name = 'reviews' TABLES = [ Categories, Companies, Movies, Users, MoviesCategory, Reviews, MoviesCompany ] with database.connection_context(): database.create_tables(TABLES, safe=True) database.commit()
address = TextField(unique=True, index=True) balance = BigIntegerField() sent = BigIntegerField() received = BigIntegerField() def to_dict(self): return { 'address': self.address, 'balance': self.balance, 'sent': self.sent, 'received': self.received, } class WalletGroupAddress(BaseModel): wallet = UUIDField(index=True) address = TextField(index=True, unique=True) class WalletGroupAddressMerge(BaseModel): wallet = UUIDField(index=True) address = TextField(index=True, unique=True) db.connect() # db.drop_tables([Block, Transaction, Address, AddressChanges, Message]) db.create_tables([ Block, Transaction, WalletGroup, Address, WalletGroupAddress, WalletGroupAddressMerge, AddressChanges, Message, Utxo ])
from peewee import SqliteDatabase, PostgresqlDatabase, Model, CharField, DateTimeField # SQLite database using WAL journal mode and 64MB cache. # sqlite_db = SqliteDatabase('my_database.db') db = PostgresqlDatabase( 'library', user='******', password='******', host='46.30.164.249', port=5432 ) class GoogleImage(Model): keyword = CharField() image_url = CharField(max_length=1024) date = DateTimeField() class Meta: database = db table_name = 'images_from_google' if __name__ == '__main__': db.connect() db.drop_tables([GoogleImage]) db.create_tables([GoogleImage])
class Meta: database = db class Image(Base): origin_image = CharField() extract_image = CharField(unique=True, primary_key=True) db.connect() conn = psycopg2.connect(dbname="database_name", user="******", host='127.0.0.1', password="******", port=1234) db.create_tables(Image) def match(origin, extract): try: with db.atomic(): img = Image.create(origin_image=origin, extract_image=extract) img.save() except IntegrityError: print("The extract image exists") db.close() # match("abc980000", "abc100001") # match("abc5", "abc6") # match("abc7", "abc11")
indexes = ( (('txid', 'vout'), True), ) class Message(BaseModel): message = TextField() class AddressChanges(BaseModel): address = TextField(index=True) balance_change = BigIntegerField() sent_change = BigIntegerField() received_change = BigIntegerField() class Address(BaseModel): address = TextField(unique=True, index=True) balance = BigIntegerField() sent = BigIntegerField() received = BigIntegerField() def to_dict(self): return { 'address': self.address, 'balance': self.balance, 'sent': self.sent, 'received': self.received, } db.connect() # db.drop_tables([Block, Transaction, Address, AddressChanges, Message]) db.create_tables([Block, Transaction, Address, AddressChanges, Message, Utxo])