Python GUI wont import + SQlite ENGINE - python

As a beginner in Python i must understand this code:
from settings import PROJECT_ROOT
--> I am trying in the Python Shell to type this but Python gives me a Traceback even though i have such a module
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
--> I want to use sqlite the db that is built into Python but i really can't understand what i must do
Pardon me for the basicness of the question but i feel overwhelmed by the task i have in Python these days.
For reasons of completness this is all the code in the module which is called settings.py:
from settings import PROJECT_ROOT
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Make this unique, and don't share it with anybody.
SECRET_KEY = ''
# Python dotted path to the WSGI application used by Django's runserver; added in v1.4
WSGI_APPLICATION = 'wsgi.application'
############### PYSEC specific variables
# assumes this directory exists
DATA_DIR = "%s/pysec/data/" % PROJECT_ROOT
UPDATE
I dont want to stress your already overstressed patience but why does it keep telling me the SECRET_KEY value is empty? I put
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'sdfgtardyure34654356435'
and it gives me ths in text
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
Here it is in a pic in the cmd

Try using python manage.py shell to open the python shell.
Usually the settings.py file reside inside the project root directory, so in order to import the PROJECT_ROOT variable, you can use from project_name.settings import PROJECT_ROOT
[EDIT]
To use the sqlite engine, change the DATABASES dictionary to:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(PROJECT_ROOT, '/project_database/db_name.sqlite3'),
}
}
2[EDIT]
There's no stress. Like a tip, see this Adding Python Path on Windows 7 question to add the python files to the win path variable, this help you to avoid to put your projects inside c:PythonXX, and use another directory instead.
I've take a look at the linked github project, and it seems to explain inside the README file that you must add a SECRET_KEY and a DATA_DIR variables.
Here's a workaround I've done to get work that project:
$ git clone https://github.com/lukerosiak/pysec.git
$ cd pysec
$ ls # the dir command when on Windows
README.md
TODO.md
local_settings-example.py
manage.py*
pysec/
requirements.txt
settings.py*
$ cp local_settings-example.py local_settings.py
Edit the local_settings.py file and modify the SECRET_KEY and DATA_DIR variables:
SECRET_KEY = '#r65u-33&#2v3vu-e^h-%u4kg=g9y5z'
DATA_DIR = '/home/slacker/pysec/project_database' # or something like: C:\\users\tosh\pysec\
project_database
Run:
$ python manage.py syncdb
I hope it can help!

Related

Django can't find me .env variables? decouple.UndefinedValueError: ENVIORNMENT not found. Declare it as envvar or define a default value

I am very new to Django and trying to configure python-decouple to use .env variables. I am getting DB_PASSWORD not found. Declare it as envvar or define a default value. when trying to run the server. The .env file is located in the root directory. Here is my code:
raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option))
decouple.UndefinedValueError: ENVIORNMENT not found. Declare it as envvar or define a default value.
settings.py
from decouple import config
from secrets_manager import get_secret
environment = config("ENVIRONMENT")
SECRET_KEY = get_secret(environment).get("SECRET_KEY")
DEBUG = config("DEBUG", default=False, cast=bool)
DATABASES = {
"default": {
"ENGINE": config("DB_ENGINE"),
"NAME": config("DATABASE_NAME"),
"USER": config("DB_USER"),
"PASSWORD": config("DB_PASSWORD"),
"HOST": config("DB_HOST"),
"PORT": config("DB_PORT", cast=int),
"OPTIONS": {
"init_command": "SET foreign_key_checks = 0;",
},
}
}
.env
SECRET_KEY='nvyj6_-&m#lg87$%l3###+r046ioem^18+ql*)t)'
DEBUG=True
DB_ENGINE=django.db.backends.mysql
DATABASE_NAME=blogs
DB_USER=root
DB_PASSWORD=
DB_HOST=127.0.0.1
DB_PORT=3306
Django==3.1.4 python-decouple==3.3
You are using config('ENVIRONMENT') in your code, without a corresponding ENVIRONMENT setting in your .env file. Make sure:
your .env file is at the root directory of your project.
you spell ENVIRONMENT consistently in your .env file and in your settings.py file wherever you use it.

Netmiko and Textfsm Path and Env Issue Windows

I am currently trying to set up a test with Netmiko and Textfsm in Windows 10, but no matter what path I try to setup the textfsm environment variable, it still doesn't pick it up and throws an error:
Valid ntc-templates not found, please install https://github.com/networktocode/ntc-templates
and then set the NET_TEXTFSM environment variable to point to the ./ntc-templates/templates
directory.
I tried setting the environment variable manually via system properties --> environment variables, but still get the same message. I tried absolute as well as relative paths and no go. Ideally a relative path as the template folder will alway be alongside the script calling it. It might be something simple but im totally missing it right now.
The folder structure:
My Code:
import os, json
from netmiko import Netmiko
from netmiko import NetMikoAuthenticationException
templates = os.path.dirname(os.path.abspath(__file__)) + '\\ntc-template\\templates\\'
os.environ['NET_TEXTFSM']= templates
print(os.environ['NET_TEXTFSM'])
###############################################################
#Can i set the env var from within the scirpt using python?
#os.system(f'cmd /c "set NET_TEXTFSM={templates}"')
###############################################################
switch = {'device_type': 'cisco_ios',
'ip': '192.168.0.20',
'username': 'cisco',
'password': 'cisco',
'secret': 'cisco',
'timeout': 10000,
'session_timeout': 10000}
try:
c = Netmiko(**switch)
c.enable()
show_ip_arp = c.send_command('show ip arp', use_textfsm=True)
print(json.dumps(show_ip_arp))
except Exception as e:
print(e)
I was hoping anyone points to what might be wrong or missing. I would love to avoid having to set up any environment variables via cmd unless it can be automated as well. The idea is whoever opens this py file gets all that's needed to use textfsm.
Issue resolved with the help of the netmiko repository owner:
The code below works with the following libs and version:
netmiko==3.1.0
ntc-templates==1.4.0
textfsm==1.1.0
import os, json
import ntc_templates
from netmiko import Netmiko
from netmiko import NetMikoAuthenticationException
switch = {'device_type': 'cisco_ios',
'ip': '192.168.0.20',
'username': 'cisco',
'password': 'cisco',
'secret': 'cisco',
'timeout': 10000,
'session_timeout': 10000}
try:
c = Netmiko(**switch)
c.enable()
show_ip_arp = c.send_command('show ip arp', use_textfsm=True)
print(show_ip_arp)
except Exception as e:
print(e)

Python name 'os' is not defined [duplicate]

This question already has answers here:
NameError: name 'datetime' is not defined
(2 answers)
Closed 4 years ago.
I am trying to run this python module
from settings import PROJECT_ROOT
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME' : os.path.join(BASE_DIR, 'db_name.sqlite3'),
}
}
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'sdfgtardyure34654356435'
# Python dotted path to the WSGI application used by Django's runserver; added in v1.4
WSGI_APPLICATION = 'wsgi.application'
############### PYSEC specific variables
# assumes this directory exists
DATA_DIR = "%s/pysec/data/" % PROJECT_ROOT
But whenever i try to run it by F5 i get this
Traceback (most recent call last):
File "C:\Python27\pysec-master\local_settings-example.py", line 11, in <module>
'NAME' : os.path.join(BASE_DIR, 'db_name.sqlite3'),
NameError: name 'os' is not defined
The module lives in the C:\Python27\pysec-master and i got pysec for here
Do you know what must i do to run the module with success?
Just add:
import os
in the beginning, before:
from settings import PROJECT_ROOT
This will import the python's module os, which apparently is used later in the code of your module without being imported.
The problem is that you forgot to import os. Add this line of code:
import os
And everything should be fine.
Hope this helps!

Using django.test.client to test app http requests, getting errors

We're beginning to write unit tests for our API (created with the Django Rest Framework). We decided to start off simple and use the built in unittest and django.test.client classes. I've got the stub of a test written and it runs just fine:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import unittest
# from django.test.client import Client
class TestGrowth(unittest.TestCase):
def setUp(self):
# self.client = Client()
pass
def test_numbers_3_4(self):
self.assertEqual(4, 4, True)
def test_strings_a_3(self):
self.assertEqual('andy', 'andy', True)
def suite():
suite = unittest.TestSuite()
# Add test cases to suite
suite.addTests(unittest.makeSuite(TestGrowth))
return suite
if __name__ == '__main__':
# Run test suite
unittest.TextTestRunner(verbosity=2).run(suite())
However as soon as I uncomment the line reading from django.test.client import Client I get an error:
Traceback (most recent call last):
File "./AccountGrowth.py", line 8, in <module>
from django.test.client import Client
File "/home/vagrant/.virtualenvs/emmasocial/lib/python2.7/site-packages/django/test/__init__.py", line 5, in <module>
from django.test.client import Client, RequestFactory
File "/home/vagrant/.virtualenvs/emmasocial/lib/python2.7/site-packages/django/test/client.py", line 21, in <module>
from django.db import close_connection
File "/home/vagrant/.virtualenvs/emmasocial/lib/python2.7/site-packages/django/db/__init__.py", line 11, in <module>
if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
File "/home/vagrant/.virtualenvs/emmasocial/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/home/vagrant/.virtualenvs/emmasocial/lib/python2.7/site-packages/django/conf/__init__.py", line 46, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured.
You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
We are defining DATABASES in settings.py as follows:
if "DATABASE_URL" in os.environ:
# Parse database configuration from $DATABASE_URL
DATABASES = {
'default': dj_database_url.config()
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'emmasocial', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
I'm running the tests from within the vagrant shell inside <app>/api/tests with the following command python ./AccountGrowth.py.
Can anyone shed some light on why this is happening?
You're not running the tests via Django's test runner, which sets all that up for you. You don't need that if __name__ == '__main__' block or its explicit call to run(), and you should run your tests via ./manage.py test.

Where is the sqlite database file created by Django?

I've got python installed and sqlite is included with it... but where is the sqlite db file path that was created with manage.py syncdb? I'm on a mac.
In the settings.py file, there is a variable called DATABASES. It is a dict, and one of its keys is default, which maps to another dict. This sub-dict has a key, NAME, which has the path of the SQLite database.
This is an example of a project of mine:
CURRENT_DIR= '/Users/brandizzi/Documents/software/netunong'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': CURRENT_DIR+ '/database.db', # <- The path
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
You can easily retrieve this value using the Django shell that is accessible running the command python manage.py shell. Just follow the steps below:
>>> import settings
>>> settings.DATABASES['default']['NAME']
'/Users/brandizzi/Documents/software/netunong/database.db'
If the returned value is some relative path, just use os.path.abspath to find the absolute one:
>>> import os.path
>>> os.path.abspath(settings.DATABASES['default']['NAME'])
'/Users/brandizzi/Documents/software/netunong/database.db'
if settings not available then this could embedded in your packageName/base Directory:
try:
import packageName
import os.path.abspath
In [3]: os.path.abspath(packageName.DATABASES['default']['NAME'])`
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-3-ca6dcbd75c6d> in <module>()
----> 1 os.path.abspath(settings.DATABASES['default']['NAME'])
>>> NameError: name 'settings' is not defined
>>> os.path.abspath(packageName.settings.DATABASES['default']['NAME'])`
>>> '/Users/brandizzi/Documents/software/netunong/database.db'

Categories