importing the connection of a file. py

Asked

Viewed 58 times

0

Good morning, use Peewee with Postgresql, working very well.

The connection credentials are as follows::

db = PostgresqlDatabase (
                        'ALTERDATA_WSHOP', # Required by Peewee.
                        user = 'postgres', # Will be passed directly to psycopg2.
                        password = '# abc123 #', # Ditto.
                        host = 'localhost') # Ditto.

How do I save this to a. py file and recover this information if any?

Below my code:

from datetime import datetime
from peewee import (PostgresqlDatabase, CompositeKey, Model, CharField, DateTimeField, 
               DoubleField, IntegerField, TextField, BooleanField)

def open_config_pg():
    try:
        with open('pg_config.py', 'r') as f:
            # Conteúdo do arquivo
            db = f.read()

    except:
        text = "PostgresqlDatabase('ALTERDATA_WSHOP', user='postgres', password='#abc123#', host='localhost')"

        with open('pg_config.py', 'w') as f:
            # Conteúdo do arquivo
            f.write(text) 

        with open('pg_config.py', 'r') as f:
            # Conteúdo do arquivo
            db = f.read()

return db 

class UnknownField(object):
    def __init__(self, *_, **__): pass


class BaseModel(Model):  

    class Meta:
        db = open_config_pg()
        database = db

My return is this:

"/home/Elias/. pyenv/versions/3.8.3/lib/python3.8/site-Packages/Peewee.py", line 2150, at _execute cursor = database.execute (self) Attributeerror: object 'str' has no 'run' attribute'

  • Return is out of function.

  • It is true! But unfortunately it returned another error: raise Valueerror('Query has not been executed.') Valueerror: Query has not been executed.

  • See that what you are reading from the file is the text of a program. Simply reading the text and returning does not make it run, it is just a string pro Python. Actually, you should write the connection parameters into the file and call the code with them. An easy solution is to use json

1 answer

0


Whoa, try it with this:

import json
from datetime import datetime
from peewee import (PostgresqlDatabase, CompositeKey, Model, CharField, DateTimeField, 
                    DoubleField, IntegerField, TextField, BooleanField)


default_ config = {"banco": "ALTERDATA_WSHOP", 
                   "user": "postgres", 
                   "password": "#abc123#",
                   "host": "localhost"}


def save_config_pg(config):
    with open('pg_config.json', 'w') as f:
        f.write(json.dumps(config))


def open_config_pg():
    try:
        with open('pg_config.json', 'r') as f:            
            config = json.loads(f.read())
    except Exception:        
        config = default_config
        save_config_pg(config)
    return PostgresqlDatabase(config["banco"], user=config["user"], password=config["password"], host=config["host"])

class UnknownField(object):
    def __init__(self, *_, **__): pass


class BaseModel(Model):  

    class Meta:
        db = open_config_pg()
        database = db

You can try reading a file. py, but it is a little harder as you would have to import and handle the error if import does not exist. I prefer a configuration file even.

With import would look like this:

from datetime import datetime
from peewee import (PostgresqlDatabase, CompositeKey, Model, CharField, DateTimeField, 
               DoubleField, IntegerField, TextField, BooleanField)

def open_config_pg(n=0):
    try:
        from pg_config import db        
    except ImportError:
        text = """
from peewee import PostgresqlDatabase
db = PostgresqlDatabase('ALTERDATA_WSHOP', user='postgres', password='#abc123#', host='localhost')\n"""
        with open('pg_config.py', 'w') as f:
            # Conteúdo do arquivo
            f.write(text) 
        if n == 1:
            raise
        return open_config_pg(1)
    return db


class UnknownField(object):
    def __init__(self, *_, **__): pass


class BaseModel(Model):  

    class Meta:
        db = open_config_pg()
        database = db
  • Good morning my friends! nmenezes, perfect output. Thanks, it worked!

  • I still prefer the json solution. Using a . py for this can cause other problems, especially since the file would have to be in the import path. A json can be opened from anywhere and you don’t run the risk of the user writing something wrong in the program.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.