Django: Improperly configured url: unbalanced parenthesis - python

I'm developing a website ina VM on my Mac which then gets deployed to a remote UAT server. The VM is set up with the same OS and software stack as the UAT and live servers. I'm getting the following error when attempting to access the UAT version of my website:
"^accounts/update-user-group/(?P<pk>\d" is not a valid regular expression: unbalanced parenthesis
On first look it seems pretty obvious what's wrong: The given URL pattern is incomplete. However, my urls.py file has the correct full url:
# -*- coding: utf-8 -*-
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.conf.urls import patterns, url
from views import UserGroupList, UserGroupDetail
from views import UserGroupCreate, UserGroupUpdate, UserGroupDelete
from views import UserDeletedGroups, RecoverDeletedGroup
urlpatterns = patterns('',
url(_(r'^accounts/create-user-group/$'), UserGroupCreate.as_view(), name='user_group_create'),
url(_(r'^accounts/update-user-group/(?P<pk>\d+)/$'), UserGroupUpdate.as_view(), name='user_group_update'),
url(_(r'^delete/(?P<pk>\d+)/$'), UserGroupDelete.as_view(), name='user_group_delete'),
url(_(r'^accounts/user-group-deleted/$'), UserDeletedGroups.as_view(), name='user_group_deleted_list'),
url(_(r'^recover/(?P<pk>\d+)/$'), RecoverDeletedGroup.as_view(), name='user_group_recover_deleted'),
url(_(r'^accounts/user-group-details/(?P<pk>\d+)/$'), UserGroupDetail.as_view(), name='user_group_detail'),
url(_(r'^accounts/user-group-list/$'), UserGroupList.as_view(), name='user_group_list'),
)
So the error seems to be getting generated by the second regex in the urlpatterns. However, If I change the regex to this:
url(_(r'^accounts/update-user-group/(?P<pk>[\d]+)/$'), UserGroupUpdate.as_view(), name='user_group_update'),
Then the error moves on to the next line. All I've done here is add square brackets round the \d
for the pk argument. How can this simple difference be the cause of the error? And why would it only be happening in my UAT environment and not local development?

Daniels question pointed me in the right direction for this. The translation for the problem URL in my PO file was incomplete so ensuring that was correct sorted my problem.

Related

Redirect hostname/endpoint to api.hostname/endpoint in django

I have my api built with this pattern: api.hostname/endpoint.
However there is a plugin to my app that uses hostname/endpoint pattern.
I would like to solve it on the backend side by adding redirection to api.hostname/endpoint.
I tried to experiment with adding urls or paths to urlpatterns, but it didn't help me.
How can I achieve it? Any ideas?
Regards,
Maciej.
You can use urllib
import urllib.parse
url = "https://hostname/endpoint"
split_url = urllib.parse.urlsplit(url)
result = f"{split_url.scheme}://api.{split_url.hostname}/{split_url.endpoint}"
print(result)
>> "https://api.hostname/endpoint"

Django Export data from postGre to shapeFile

I'm new in django and python.
I've tried to export database data to shapefile using https://bitbucket.org/springmeyer/django-shapes/src
and i got a Segmentation fault. is there is anyway to make this work by only using django GeoDjango?
That's a non-updated project. You can check this a bit more up to date fork.
To check quickly if it works for you download the zip and copy the shape-engine folder inside your django project.
Install fiona (pip install fiona)
Add a new url to download the shapfile like
from .views import export
urlpatterns = urlpatterns + [ url(r'^worldshapes/', export_worldshapes), ]
And a new view:
from shape_engine.shape_responder import ShpResponder
def export(request):
from .models import WorldBorders
w = WorldBorders.objects.all()
shp_response = ShpResponder(w)
shp_response.file_name = 'World Borders'
return shp_response()
django-shape-engine only works in python 2.x. A couple of changes should be made to work with it in python 3. Basically, use BytesIO instead of StringIO

Django JSON_RPC doesn't work

i want to create a simple Django(1.3) project that uses JSON-RPC. i use this implementation:
django-json-rpc
and this is my project files:
urls.py:
from django.conf.urls.defaults import patterns, include, url
from myapp.views import *
from jsonrpc import jsonrpc_site
urlpatterns = patterns('',
url(r'^json/browse/', 'jsonrpc.views.browse', name="jsonrpc_browser"),
url(r'^json/', jsonrpc_site.dispatch, name="jsonrpc_mountpoint"),
(r'^json/(?P<method>[a-zA-Z0-9.]+)$', jsonrpc_site.dispatch),
)
views.py:
from jsonrpc import jsonrpc_method
#jsonrpc_method('sayHello')
def hello(request, name='Lester'):
return "Hello %s" % name
when i test this code in JSON-RPC Browser(included with the library) it doesn't work. whe is want to add this import in the shell:
from jsonrpc.proxy import ServiceProxy
i get the response like this:
Error:
what's the problem here? it seems a simple process but it doesn't work for me.
i found the solution. in fact json-rpc works but in JSON-RPC Browser i have to treat with some difference than regular way. according to here, we should initialize and call json-rpc methods like this:
from jsonrpc.proxy import ServiceProxy
s = ServiceProxy('http://localhost:8080/json/')
s.myapp.sayHello('Sam')
but it's not true! this method is correct when we use it in django shell or in our main code! in JSON-RPC Browser we just need to call our method like this:
jsonrpc.sayHello('sam')
just that!
thanks to all.

Python flask flash message exception remains after restarting

I'm making a small flask app where I had something like this:
#app.route('/bye')
def logout():
session.pop('logged_in', None)
flash('Adiós')
return redirect('/index')
Needless to say when I ran the application and I navigated to '/bye' it gave me a UnicodeDecodeError. Well, now it gives me the same unicodedecodeerror on every page that extends the base template (which renders the messages) even after restarting the application. and always with the same dump() despite removing that flash in the source code. All I can think of is what the crap? Help please.
Well I had to restart my computer to clear the stupid session cache or something.
I think that flash() actually creates a session called session['_flashes']. See this code here. So you will probably have to either:
clear/delete the cookie
OR
session.pop('_flashes', None)
Flask flashing stores the messages in a session cookie until they are succesfully "consumed".
If you get a UnicodeDecodeError (https://wiki.python.org/moin/UnicodeDecodeError) in this case the messages is not consumed, so you get the error again and again.
My solution was to delete the cookie from the browser
Since I had the problem when using localization, I solved the cause now by installing my translation object like:
trans = gettext.GNUTranslations(...)
trans.install(unicode=True)
and having UTF-8 encoding in my python source files and "Content-Type: text/plain; charset=UTF-8\n" in the translation file (.pot)
You're using an non ascii string "adiós", so you need to ensure that python will process strings as unicode, not as ascii.
Add this to the header of your python file. This will tell the compiler that your file contains utf8 strings
#!/usr/bin/env python
# -*- coding: utf-8 -*-
so your code will be something like this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask
app = Flask()
#app.route('/bye')
def logout():
session.pop('logged_in', None)
flash('Adiós')
return redirect('/index')

web.py url handling: multiple subapplication redirection

When using web.py framework. you can redirect an url to a subapplication.
e.g (code.py):
import web
import subapp1
urls = (
"/sub1", subapp1.app,
"/(.*)", "index"
)
....
this is really straight forward.
However, when writing subapp1.py which has its own url handlers, if i want to re-route some url, say '/sub2', to another subapplication (subapp2), i am failing.
Formerly in subapp1.py
import web
import subapp2
urls = (
"/sub2", subapp2.app,
"/(.*)", "some_local_class"
)
....
GET request to "/sub1/sub2/", is handled by "some_local_class" in supapp1.py. But i need this url is re-routed to subapp2.py.
Is there anything i am missing? Or may be this is not recommended url handling methodology in web.py?
After some trial-error, found that there is nothing wrong with web.py and rerouting from subapp to another subapp. It is all working perfectly.
What is wrong is my method. Do not try to create a subapp in package's init.py file. At least when i moved subapp to its own module, it all worked well.

Categories

Resources