I am trying to build a one time script by passing in a django request in order to build an absolute URI.
I am using the HttpRequest() method as follows...
request = HttpRequest()
And passing it into the function that I am calling when running my script.
I keep running into a KeyError
My script that is being ran is as follows,
from django.http import HttpRequest
for form in forms:
form_data = get_data(form)
for user in User.objects.all():
request = HttpRequest()
config_user_forms(request, user)
Errors out with the following,
File "config_user_forms.py", line 65, in <module>
redeploy_form(request, user)
File "/tmp/8dae22604556cc2/users/admin/users.py", line 654, in redeploy_form
build_url = request.build_absolute_uri(
File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 223, in build_url
location = self._current_scheme_host + location
File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/utils/functional.py", line 45, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 240, in _current_scheme_host
return "{}://{}".format(self.scheme, self.get_host())
File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 121, in get_host
host = self._get_raw_host()
File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 111, in _get_raw_host
host = self.META["SERVER_NAME"]
KeyError: 'SERVER_NAME'
I am a bit stumped on a work around, and appreciate any help in advance!
Related
I am using python-socketio client to define events that will manipulate the database once triggered but i am getting the "Working outside app context" error.
#socketio.event
def my_event(data):
id = data["id"]
user = User.query.get(id)
print("Debug Text")
File "/home/allan/Documents/proj/Onsite/proj_backend/proj/websocket/routes.py", line 20, in complete_online_booking
user = User.query.get(id)
^^^^^^^^^^^^^^^^^^^^
File "/home/allan/Documents/proj/Onsite/proj_backend/venv/lib/python3.11/site-packages/flask_sqlalchemy/__init__.py", line 552, in __get__
return type.query_class(mapper, session=self.sa.session())
^^^^^^^^^^^^^^^^^
File "/home/allan/Documents/proj/Onsite/proj_backend/venv/lib/python3.11/site-packages/sqlalchemy/orm/scoping.py", line 47, in __call__
sess = self.registry()
^^^^^^^^^^^^^^^
File "/home/allan/Documents/proj/Onsite/proj_backend/venv/lib/python3.11/site-packages/sqlalchemy/util/_collections.py", line 1010, in __call__
return self.registry.setdefault(key, self.createfunc())
^^^^^^^^^^^^^^^^^
File "/home/allan/Documents/proj/Onsite/proj_backend/venv/lib/python3.11/site-packages/sqlalchemy/orm/session.py", line 4274, in __call__
return self.class_(**local_kw)
^^^^^^^^^^^^^^^^^^^^^^^
File "/home/allan/Documents/proj/Onsite/proj_backend/venv/lib/python3.11/site-packages/flask_sqlalchemy/__init__.py", line 174, in __init__
self.app = app = db.get_app()
^^^^^^^^^^^^
File "/home/allan/Documents/proj/Onsite/proj_backend/venv/lib/python3.11/site-packages/flask_sqlalchemy/__init__.py", line 1042, in get_app
raise RuntimeError(
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/
I'm using sessions in a current django project and recently got a 'Object of type 'date' is not JSON serializable' error - due to the move_in_date field below.
When saving a modelform of the below model to the session via:
if form.is_valid():
request.session.update(form.cleaned_data)
my model:
class Address(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
house_name_number = models.CharField(max_length=255, verbose_name="house name or number")
street_name = models.CharField(max_length=255)
town_city = models.CharField(max_length=255)
county = models.CharField(max_length=255)
postcode = models.CharField(max_length=8)
same_address = models.BooleanField()
move_in_date = models.DateField(null=True, blank=True)
I've tried to solve the issue by using DjangoJSONEncoder as suggested by the docs, which can handle datetimes via the settings with SESSION_SERIALIZER=DjangoJSONEncoder (should this be a serializer rather than an encoder?), but trying that or SESSION_SERIALIZER=PickleSerializer both give an Attribute error - ... has no attribute 'rsplit'
Additionally I was using django wizard before which stores intermediate data (such as the field causing the date issue above) in the session. I've now switched that part of the app to use seperate views for flexibility (as signup wasn't just a linear path), django wizard doesn't have this issue, how does it get round this?
Updated with stacktrace
Traceback (most recent call last):
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/utils/deprecation.py", line 142, in __call__
response = self.process_response(request, response)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/contrib/sessions/middleware.py", line 58, in process_response
request.session.save()
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py", line 83, in save
obj = self.create_model_instance(data)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py", line 69, in create_model_instance
session_data=self.encode(data),
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py", line 98, in encode
serialized = self.serializer().dumps(session_dict)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/core/signing.py", line 93, in dumps
return json.dumps(obj, separators=(',', ':')).encode('latin-1')
File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'date' is not JSON serializable
Stack trace for trying DjangoJSONEncoder:
Traceback (most recent call last):
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/utils/deprecation.py", line 138, in __call__
response = self.process_request(request)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/contrib/sessions/middleware.py", line 20, in process_request
request.session = self.SessionStore(session_key)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py", line 18, in __init__
super(SessionStore, self).__init__(session_key)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py", line 51, in __init__
self.serializer = import_string(settings.SESSION_SERIALIZER)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/utils/module_loading.py", line 15, in import_string
module_path, class_name = dotted_path.rsplit('.', 1)
AttributeError: type object 'DjangoJSONEncoder' has no attribute 'rsplit'
A few things of confusion are hitting you:
When setting the serializer, do not provide a class reference, but a dotted part. This is seen in the error:
module_path, class_name = dotted_path.rsplit('.', 1)
DjangoJSONEncoder isn't the right fix for a serializer. It is referenced in the documentation as a way to serialize models before putting them into the session.
If you want to make a smart serializer then you still need to create a Serializer, which should support a dumps and loads interface, that leverage a JsonEncoder and JsonDecoder respectively.
The Pickle serializer will work just fine, but as said you need to provide the dotted path.
If you want to use JSON as serializer, then this might be a good start:
from django.core.serializers.json import DjangoJSONEncoder
from django.core.signing import JSONSerializer as BaseJSONSerializer
class SmartJSONSerializer(BaseJSONSerializer):
def dumps(self, obj):
return json.dumps(obj, separators=(',', ':'), cls=DjangoJSONEncoder).encode('latin-1')
Hi I am new to python and trying to make a rest call to an API useing requests.
My code is
import requests
import json
from pprint import pprint
#json_file='a.json'
json_file='apiInput.json'
hdr_key=[]
hdr_value=[]
json_data=open(json_file)
data = json.load(json_data)
request_body={}
#pprint(data)
json_data.close()
request_data = data['request1']
request_header=request_data['header-data']
url=request_header['url']
cert='/Somepath/clientid.pem'
if 'body' in request_data:
request_body=request_data['body']
r = requests.get(url, headers=request_header, cert=('/Somepath/clientid.pem','weblogic'))
print r.status_code
print r.json()
I am getting the following error
Traceback (most recent call last):
File "/Users/tsu892/Desktop/Office/Pythone-work/ASR-pythone/ASR-Application/asrmain.py", line 29, in <module>
r = requests.get(url, headers=request_header, cert=('/Users/tsu892/Desktop/Office/ASR/asr-asrint-branch/rtmqa-clientid.pem','weblogic'))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/api.py", line 72, in get
return request('get', url, params=params, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/sessions.py", line 508, in request
resp = self.send(prep, **send_kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/sessions.py", line 618, in send
r = adapter.send(request, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/adapters.py", line 407, in send
self.cert_verify(conn, request.url, verify, cert)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/adapters.py", line 251, in cert_verify
"invalid path: {0}".format(conn.key_file))
IOError: Could not find the TLS key file, invalid path: weblogic
I have .PEM file and a password used for the key. I have a ruby code that looks like:
if url.scheme == "https"
http.use_ssl = true
http.key = OpenSSL::PKey::RSA.new(File.read("/Somepath/clientid.pem"), "weblogic")
http.cert = OpenSSL::X509::Certificate.new(File.read("/Somepath/clientid.pem"))
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
In the ruby code the .key option in http allows me to open the certfile using the password to get the key. I don't know how to do this or similar to this in python.
Could anyone please help !!!!
I am not new to App Engine, but am just getting started with the Python stack on it. I am using webapp2 and Cygwin with its own Python. I am trying to implement custom authentication, relying on sessions.. I am following numerous examples of enabling sessions using webapp2-extras module. I have the following relevant code:
import webapp2
from webapp2_extras import sessions
class BaseHandler(webapp2.RequestHandler):
def dispatch(self):
self.session_store = sessions.get_store(request=self.request)
try:
webapp2.RequestHandler.dispatch(self)
finally:
self.session_store.save_sessions(self.response)
#webapp2.cached_property
def session(self):
return self.session_store.get_session(self.response, backend='datastore')
class CounterHandler(BaseHandler):
def get(self):
cnt_key = 'cnt'
if cnt_key in self.session:
cnt = int(self.session[cnt_key])
else:
cnt = 0
cnt += 1
self.session[cnt_key] = str(cnt)
self.response.headers['Content-Type'] = 'text/plain'
self.response.write("Hello, world!")
This fails with the following stack trace:
Traceback (most recent call last):
File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/cygdrive/c/Documents and Settings/dev/My Documents/proj/easytime_gae/src/handlers.py", line 11, in dispatch
self.session_store.save_sessions(self.response)
File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2_extras/sessions.py", line 420, in save_sessions
session.save_session(response)
File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2_extras/appengine/sessions_ndb.py", line 117, in save_session
response, self.name, {'_sid': self.sid}, **self.session_args)
File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2_extras/sessions.py", line 423, in save_secure_cookie
value = self.serializer.serialize(name, value)
File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2_extras/securecookie.py", line 48, in serialize
signature = self._get_signature(name, value, timestamp)
File "/cygdrive/c/google_appengine/lib/webapp2-2.5.2/webapp2_extras/securecookie.py", line 103, in _get_signature
signature.update('|'.join(parts))
TypeError: sequence item 0: expected string, Response found
The error goes away if I disable the line that writes to the session object and leave reading from sessions intact:
# self.session[cnt_key] = str(cnt)
Any help would be much appreciated.
The first argument to get_session is the name, if you want to change from the default. You are passing a response object, which is wrong.
#webapp2.cached_property
def session(self):
return self.session_store.get_session(backend='datastore')
I have deployed my django app using Apache and mod_wsgi. All of the settings load fine, but when I redirect the user to the login page, I get the following error:
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/django/core/handlers/base.py", line 83, in get_response
request.path_info)
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/django/core/urlresolvers.py", line 186, in resolve
sub_match = pattern.resolve(new_path)
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/django/core/urlresolvers.py", line 125, in resolve
return self.callback, args, kwargs
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/django/core/urlresolvers.py", line 137, in _get_callback
raise ViewDoesNotExist, "Tried %s in module %s. Error was: %s" % (func_name, mod_name, str(e))
ViewDoesNotExist: Tried login in module django.contrib.auth.views. Error was: 'module' object has no attribute '__file__'
With or with out the login redirect in place, I get this error when trying to load the /admin site.
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/django/core/handlers/base.py", line 92, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 164, in wrapper
return self.admin_view(view)(*args, **kwargs)
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 155, in inner
return self.login(request)
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 253, in login
return self.display_login_form(request, message)
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 349, in display_login_form
'title': _('Log in'),
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/django/utils/translation/__init__.py", line 62, in ugettext
return real_ugettext(message)
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/django/utils/translation/trans_real.py", line 286, in ugettext
return do_translate(message, 'ugettext')
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/django/utils/translation/trans_real.py", line 276, in do_translate
_default = translation(settings.LANGUAGE_CODE)
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/django/utils/translation/trans_real.py", line 194, in translation
default_translation = _fetch(settings.LANGUAGE_CODE)
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/django/utils/translation/trans_real.py", line 181, in _fetch
apppath = os.path.join(os.path.dirname(app.__file__), 'locale')
AttributeError: 'module' object has no attribute '__file__'
I have another django powered site on this same server that runs fine even in the admin site. I am stumped as to why this behavior has popped up on this site but not on the other.
Any help would be greatly appreciated!
This is a bit of an old post, but I found it so someone else might.
That urlresolver error in django happens when there's a problem compiling your view (or something imported by your view). Sadly, the stack trace seems to be incomplete; what comes up in the browser gives absolutely no indication of where the problem really lies.
Here's how I fixed my issue:
Go into the top level directory for your django app (the one with settings.py and manage.py)
run : python manage.py shell
that will drop you into a python interpreter. From there, do : import appname.viewWithProblems
that should throw an Exception that includes the stack trace you'll need to find the problem.
Hope someone else out there doesn't have the night I had last night!
Is your app in an archive, such as a .zip or .egg file? If so, modules loaded from it won't have __file__ set.