Here you can see the errors I get.
I am trying to render a pdf from a html template using Django.
This worked pretty well locally when I was fiddling about with it.
Managed to get a .pdf file from it.
Now I'm stuck with this error claiming that the uri has no attribute encode.
Has anyone had a similar error while using this python package? If so, how did you manage to fix it?
from __future__ import print_function
import easy_pdf
from deliveries.models import Delivery
from django.conf import settings
from easy_pdf.views import PDFTemplateView
import os
import sys
from django.core.wsgi import get_wsgi_application
from scripts import messages as msg
basename = os.path.splitext(os.path.basename(__file__))[0]
def run(*args, **kwargs):
if len(args) < 1 or args[0] is None:
print(msg.GeneralMessages.ERROR_DELIVERY_MISSING, file=sys.stderr)
sys.exit(1)
if not str(args[0]).isdigit():
logger.error(msg.GeneralMessages.ERROR_DELIVERY_INVALID)
sys.exit(1)
delivery = Delivery.get(args[0])
application = get_wsgi_application()
context = ''
view = ''
encoding = 'utf-8'
print(context)
view = easy_pdf.rendering.render_to_pdf('report.html', context)
if view:
f = open('report.pdf', 'wb')
f.write(view)
f.close()
print ('Report has been exported as .pdf')
if not settings.configured:
settings.configure(
DEBUG=True,
TIMEZONE="UTC",
INSTALLED_APPS=["easy_pdf", "django.contrib.staticfiles"],
TEMPLATE_DIRS=["../../deliveries/templates"],
ROOT_URLCONF=basename,
WSGI_APPLICATION="{}.application".format(basename),
STATIC_URL='/deliveries/static'
)
Related
I am using Django 3.2
I am writing a standalone app MyApp that uses GeoIP2
I want to be able to have a project using the MyApp app, to be able to do either one of the following.
set GEOIP2_PATH in project.settings OR
(default) fall back on the GEOIP2_PATH value set in MyApp.settings
This is what I have so far:
MyApp/settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
GEOIP_PATH = os.path.join(BASE_DIR, 'userprofile/geodata')
# ...
MyApp/utils.py
from django.conf import settings
from MyApp import settings as myapp_settings
def get_attribute_from_settings(attribute_name):
try:
value = getattr(settings, attribute_name)
except AttributeError:
try:
value = getattr(myapp_settings, attribute_name)
except AttributeError:
raise ImproperlyConfigured()
finally:
return value
Code that uses GeoIP2
from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception
from ipware import get_client_ip
geo = GeoIP2()
def do_something(address):
# Barfs at next line:
info = geo.city(address)
When the function above is called, I get the following exception thrown:
raise GeoIP2Exception('GeoIP path must be provided via parameter or the GEOIP_PATH setting.')
django.contrib.gis.geoip2.base.GeoIP2Exception: GeoIP path must be provided via parameter or the GEOIP_PATH setting
How can I use the get_attribute_from_settings() to get the default GEOIP2_PATH if not set in project.settings?
I'm building a script to populate a db with info from a json but when It finishes the only saved objects is the last. What am I doing wrong? Here is my code:
def setup_environment():
pathname = os.path.dirname(sys.argv[0])
sys.path.append(os.path.abspath(pathname))
sys.path.append(os.path.normpath(os.path.join(os.path.abspath(pathname), '../')))
os.environ['DJANGO_SETTINGS_MODULE'] = 'config.settings'
setup_environment()
import django
django.setup()
from stats.models import Champion, Item #import models for django
import json
with open("champions.json", "r") as fjson:
data = json.load(fjson)
print len(data)
for i in data:
#print data[i]["name"], data[i]["key"]
champ = Champion.objects.get(key = data[i]["key"])
champ.global_kda = data[i]["global_kda"]
champ.kills = data[i]["kills"]
champ.assists = data[i]["assists"]
champ.deaths = data[i]["deaths"]
champ.save()
Link to all the code:
https://gist.github.com/zanklord/bc667dab9864af951446
Actually I don't know what I really did because I did nothing. I modified the file in gist and copied the same in my computer. Before it was right indentent as #help_asap suggested. Anyway thanks to #help_asap
I am trying to adapt the to-do list app in the Pyramid tutorial here to create a Python hangman game. My directory structure is as follows:
/tasks
tasks.py
/static
custom.css
/templates
main.html
I want to have a single view main.html (i.e., just the game title, the current picture with blanks, score, etc., and a button for each letter to guess) that gets updated every time the user chooses a letter.
I figured I could do this by dynamically creating a new HTML display with each button press, similar to the jpg serving method shown here. But upon running python tasks.py and opening http://localhost:8080/# in the browser, it gives a server error and: "OSError: [Errno 2] No such file or directory: '/templates/main.html' in the terminal.
Here's my tasks.py:
import os
import logging
from pyramid.config import Configurator
from pyramid.events import NewRequest
from pyramid.events import ApplicationCreated
from pyramid.exceptions import NotFound
from pyramid.httpexceptions import HTTPFound
from pyramid.response import FileResponse
from pyramid.view import view_config
from wsgiref.simple_server import make_server
logging.basicConfig()
log = logging.getLogger(__file__)
here = os.path.dirname(os.path.abspath(__file__))
##view_config(route_name='home', renderer='main.mako')
#def main_page(request):
# print request #just checking
# return {}
#view_config(route_name='home')
def main_page(request):
response = FileResponse(os.path.join(here,'/templates/main.html'), \
request=request, content_type='text/html')
return response
if __name__ == '__main__':
settings = {}
settings['reload_all'] = True
settings['debug_all'] = True
settings['mako.directories'] = os.path.join(here, 'templates')
config = Configurator(settings=settings)
config.include('pyramid_mako')
config.add_route('home', '/')
config.add_static_view('static', os.path.join(here, 'static'))
config.scan()
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 8080, app)
print 'server made'
server.serve_forever()
Considering the here declaration, I don't see how the file can't be found. As you can see from the commented out view_config, I tried using my initial HTML file (renamed main.mako) as the renderer at first, which worked fine and displayed the main page nicely.
But I don't think I can use that to update dynamically as desired. What am I missing here? Maybe I need to add something else to the settings dictionary?
You getting this error because you are using absolute path /templates/main.html.
Simple example how os.path.join works:
>>> os.path.join('/some/path/to/project', '/templates/main.html')
'/templates/main.html'
>>> os.path.join('/some/path/to/project', 'templates/main.html')
'/some/path/to/project/templates/main.html'
So try change os.path.join(here,'/templates/main.html') to os.path.join(here,'templates/main.html').
I'm working on a web application with Python and Google App Engine.
I tried to set the default URLFetch deadline globally as suggested in a previous thread:
https://stackoverflow.com/a/14698687/2653179
urlfetch.set_default_fetch_deadline(45)
However it doesn't work - When I print its value in one of the functions: urlfetch.get_default_fetch_deadline() is None.
Here is main.py:
from google.appengine.api import users
import webapp2
import jinja2
import random
import string
import hashlib
import CQutils
import time
import os
import httpRequests
import logging
from google.appengine.api import urlfetch
urlfetch.set_default_fetch_deadline(45)
...
class Del(webapp2.RequestHandler):
def get(self):
id = self.request.get('id')
ext = self.request.get('ext')
user_id = httpRequests.advance(id,ext)
d2 = urlfetch.get_default_fetch_deadline()
logging.debug("value of deadline = %s", d2)
Prints in the Log console:
DEBUG 2013-09-05 07:38:21,654 main.py:427] value of deadline = None
The function which is being called in httpRequests.py:
def advance(id, ext=None):
url = "http://localhost:8080/api/" + id + "/advance"
if ext is None:
ext = ""
params = urllib.urlencode({'ext': ext})
result = urlfetch.fetch(url=url,
payload=params,
method=urlfetch.POST,
headers={'Content-Type': 'application/x-www-form-urlencoded'})
if (result.status_code == 200):
return result.content
I know this is an old question, but recently ran into the issue.
The setting is placed into a thread-local, meaning that if your application is set to thread-safe and you handle a request in a different thread than the one you set the default deadline for, it can be lost. For me, the solution was to set the deadline before every request as part of the middleware chain.
This is not documented, and required looking through the source to figure it out.
I wrote this funcion on a utils.py located on the app direcroty:
from bm.bmApp.models import Client
def get_client(user):
try:
client = Client.objects.get(username=user.username)
except Client.DoesNotExist:
print "User Does not Exist"
return None
else:
return client
def to_safe_uppercase(string):
if string is None:
return ''
return string.upper()
Then when i use the function to_safe_uppercase on my models.py file, by importing it in this way:
from bm.bmApp.utils import to_safe_uppercase
I got the python error:
from bm.bmApp.utils import to_safe_uppercase
ImportError: cannot import name to_safe_uppercase
I got the solution for this problem when i change the import statement for:
from bm.bmApp.utils import *
But i can't understand why is this, why when i import the specific function i got the error?
You are doing what is known as a Circular import.
models.py:
from bm.bmApp.utils import to_safe_uppercase
utils.py:
from bm.bmApp.models import Client
Now when you do import bm.bmApp.models The interpreter does the following:
models.py - Line 1: try to import bm.bmApp.utils
utils.py - Line 1: try to import bm.bmApp.models
models.py - Line 1: try to import bm.bmApp.utils
utils.py - Line 1: try to import bm.bmApp.models
...
The easiest solution is to move the import inside the function:
utils.py:
def get_client(user):
from bm.bmApp.models import Client
try:
client = Client.objects.get(username=user.username)
except Client.DoesNotExist:
print "User Does not Exist"
return None
else:
return client
def to_safe_uppercase(string):
if string is None:
return ''
return string.upper()
You are creating a circular import.
utils.py
from bm.bmApp.models import Client
# Rest of the file...
models.py
from bm.bmApp.utils import to_safe_uppercase
# Rest of the file...
I would suggest your refactor your code so that you don't have a circular dependency (i.e. utils should not need to import models.py or vice versa).
I'm not sure I can explain the Import error, but I have three ideas. First, your function needs tweaking. You've used a reserved word 'string' as an argument. Consider renaming.
Second, what happens if you invoke ./manage.py shell, and do the import by hand. Does it give you any different?
Third, try deleting your pyc files to force django to recompile python code (this one is a very long shot...but worth eliminating)