Django orm and path import - django

Here is my file tree :
--script
..........script.py
-- emails
.........__init__.py
.........models.py
settings.py
_init_.py
manage.py
and my code in script.py
import email, getpass, imaplib, os
import datetime
import unicodedata
import time
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "../settings")
import sys
cmd_folder = os.path.realpath("../")
sys.path.append(cmd_folder)
from emails.models import Email
but i have this error :
TypeError: relative imports require the 'package' argument
How to resolve it please ?
Regards

Try something like:
os.path.realpath(os.path.dirname(os.path.realpath(__file__)) + '/..')

The solution thanks to #django
../ is incorrect for module path so :
import sys
cmd_folder = os.path.realpath(os.path.dirname(os.path.realpath(__file__)) + '/../..')
sys.path.append(cmd_folder)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Sumomo.settings")
from Sumomo.emails.models import Email
(sumomo is the name of my project)

Related

py2exe compiled .exe won't start

I compiled my prototype Application with py2exe to check its function as an exe, and run into 0 errors until I go to start it. Nothing happens. A process starts with my app name, it thinks for a few seconds, then nothing. No log file is generated. The app works great when run in python environment, but not in the compiled exe. I've given my setup code below. Any ideas? :
from distutils.core import setup
import py2exe, sys, os
import matplotlib
import FileDialog
import dateutil
sys.argv.append('py2exe')
setup( windows=['ATLAS.pyw'], data_files=matplotlib.get_py2exe_datafiles(),
options = {"py2exe": {
"includes": "decimal, datetime",
"packages": ["FileDialog", "dateutil"],
'bundle_files': 2,
'compressed': True}
},
zipfile = None
)
Hooks utilized in the Application:
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.backend_bases import key_press_handler
from pandas.sandbox.qtpandas import DataFrameWidget
from matplotlib.widgets import LassoSelector
from tkFileDialog import askopenfilename
from matplotlib.figure import Figure
import matplotlib.image as mpimg
from PySide import QtGui, QtCore
from matplotlib.path import Path
import pandas.io.sql as psql
from numpy import nonzero
import tkMessageBox as mb
from pylab import *
import pyodbc
import sys
import ttk
SOLVED:
So, using quick fingers (and compiling it with PyInstaller with the --debug option) I screen-capped the quickly-closing console window that contained the Traceback:
WindowsError: [Error 3] The system cannot find the path specified: 'C:\\path\\dateutil\\zoneinfo/*.*'
The zoneinfo file was being saved in pytz instead of dateutil. A quick rename solved the problem.
Only issue though, if you want to compile with -F or --onefile it will not work due to the initial improper naming convention. Not quite sure how to fix that though.

How to separate flask routes to another modules

I have hundreds of routes in my flask main module,
I think it need to separate those hundred of routes from the main module.
How to do it ?
#!/usr/bin/env python3
# -*- coding: utf8 -*-
from flask import request, url_for
from flask import Flask, request, jsonify
from flask_request_params import bind_request_params
from flask import g
import datetime
import pandas as pd
import pymongo
from webargs import Arg
from webargs.flaskparser import use_args, use_kwargs
import yaml
import time, functools
from pdb import set_trace
from pandas_helper import PandasHelper
import errors
from app_helper import *
from release_schedule import ReleaseSchedule
from mongo import Mongo
#app.route('/next_release', methods=["GET"])
#return_json
def next_release():
schedules = ReleaseSchedule.next_release(DB)
return pd.DataFrame([sche for sche in schedules])
...
#app.route('/last_release', methods=["GET"])
This is what blueprints were made to do.
Another alternative is flask-classy (which is awesome). I'm going to talk about the blueprint approach since that's what I know better.
If I was in your position I would want to split my routes up based on common imports.
Without knowning your application I'm going to guess that a distribution like this
parse_user_data_views.py
from webargs import Arg
from webargs.flaskparser import use_args, use_kwargs
import yaml
push_to_db_views.py
from pandas_helper import PandasHelper
from mongo import Mongo
import pymongo
import pandas as pd
import datetime
release_views.py
from release_schedule import ReleaseSchedule
import pandas as pd
#app.route('/next_release', methods=["GET"])
#return_json
def next_release():
schedules = ReleaseSchedule.next_release(DB)
return pd.DataFrame([sche for sche in schedules])
is likely distribution. We can't answer this for you, only you can.
But this allows you to separate out your application in some pretty nice ways.
in __init__.py
from flask import Flask
from yourapplication.release_views import release_views
from yourapplication.push_to_db_views import push_to_db_views
from yourapplication.parse_user_data_views import parse_user_data_views
app = Flask(__name__)
app.register_blueprint(release_views)
app.register_blueprint(push_to_db_views)
app.register_blueprint(parse_user_data_views)
Create a new file called views.py and add all your routes there. Then import views.py in your __ init __.py .

cannot import name DjangoServiceBase

I have a problem. spyne example dosn't work.
>>> django.get_version()
'1.6.5'
from spyne.util.django import DjangoComplexModel, DjangoServiceBase
ImportError: cannot import name DjangoServiceBase

Unable to import Django models in python script

My code is here.
I have tried different approach from stackoverflow and non of them worked.
import os
import sys
from django.conf import settings
sys.path.append('/var/www/iaas/horizon')
sys.path.append('/var/www/iaas/horizon/openstack_dashboard')
os.environ['DJANGO_SETTINGS_MODULE'] = 'openstack_dashboard.settings'
from bill.models import MonthlyBills
from django.contrib.auth import models
If I run python daemonize.py, here is the error message I get.
I am confused because I have already included my django project path in my sys.path
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'openstack_dashboard.settings' (Is it on sys.path?): cannot import name connection
What I am trying to achieve is to create a python-daemon, I need to have an access in my django models.
I hope someone who could point me where I am mistaking here.
You have to set up os.environ['DJANGO_SETTINGS_MODULE'] before you import settings.
The process of importing django.conf.settings will look to see if the DJANGO_SETTINGS_MODULE environment variable is set before determining white settings to load.
import os
import sys
sys.path.append('/var/www/iaas/horizon')
sys.path.append('/var/www/iaas/horizon/openstack_dashboard')
os.environ['DJANGO_SETTINGS_MODULE'] = 'openstack_dashboard.settings'
from django.conf import settings

django import client

i am trying to import the client in django for testing. but when i do, i get this wierd error:
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.
from django.utils import unittest
from django.utils import simplejson as json
from django.test.client import Client
this is how i imported the client so that i could use it for testing. can someone explain this to me please.
Try this:
import os
import sys
sys.path.append('/home/username/www/site_folder')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
from django.utils import unittest
from django.utils import simplejson as json
from django.test.client import Client
But replace project with folder name, where your settings.py is
The Client is looking for the settings.py. You could simply load the client by typing this in your project folder:
python manage.py shell
In Pycharm which I use, after following this Running Django tests in PyCharm
my problem was solved.
It's in the file > settings > Django Support, and then select the right settings.