Use different view depending on object model database value in Django - python

I am launching a 2nd version of a project, and I want the users to be able to upgrade to the new format. It's not going to be a forced upgrade, so essentially, users will say "Make my page a V2 page". The URLs for their pages will stay the same.
I'd like to be able in the view to say:
def v1_page(request, page_id):
page = get_object_or_404(Page, id=page_id)
if page.upgraded:
# use the v2 view instead (which ends with a return render_to_response('v2_base_page.html', variables))
v2_page(request, page)
else:
# load this page
Or am i going about it the wrong way? I dont want a massive if/else statement.

Function should return result of v2_page call:
def v1_page(request, page_id):
page = get_object_or_404(Page, id=page_id)
if page.upgraded:
return v2_page(request, page)
else:
# load this page

Related

Flask - render page without return

I'm working on an application, where user fills in form.
One of the fields asks for postcode. When request is sent, a separate thread runs python code using PYQT5, rendering page and scraping web, (don't want to pay for API from google) providing mileage between given postcode and set postcode. Results of this thread are saved in a file.
What i would like to do is to open a new webpage with information that the data is being checked. This page would run python code, which checks for results in a file (that takes up to few seconds) using while loop. if the result is in the file, the page redirect to another page.
Is there a way to render a page (or redirect to another page) without using RETURN? i understand that when I use return render_templates (page), rest of the code is ignored.
#app.route('/add_user', methods=['GET', 'POST'])
def add_user():
file = open('app/results_from_g.txt','w')
file.write('')
file.close()
form = AddForm()
if form.validate_on_submit():
url = 'https://google.co.uk/maps/dir/...'
def sendtogoogle(url):
os.system('python googlemaps_mileage.py ' +url)
thread1=threading.Thread(target=sendtogoogle, args=(url,))
thread1.start()
the next line of the code should be redirect to another page, and when results are in the file, either back here, or different page:
while result_from_file==0:
file = open('results_from_g.txt','r')
result_from_file = file.read()
if result_from_file =='': #means no data saved in the file yet
time.sleep(1)
elif wynik =='0': #means wrong postcode
//render page 'wrong postcode'
else:
//render page 'correct postcode

Exception handling and blank page

I was reading about Datastore exception handling here and possible errors here but I am having problems implementing it. Here's an example code of what I made.
try:
example.put()
except datastore_errors.TransactionFailedError:
self.response.write('Transaction failed, try again.')
When I try to load my page, nothing appears. I have built a little interface for interacting with my databases but that doesn't show up. If I remove the try/except statements, everything works fine.
What am I doing wrong?
Also why nothing at all is displayed? Shouldn't it display at least the HTML template and just throw an error when I try to put something in the database?
EDIT
Added handler code, more info
What I am doing here is I have a page where I choose a database. Depending on my choice, I open up a template I've made for adding easily instances to that database. So far I've made a template only for one database. I'm also using MathJax library and have check button to check the input before posting it.
When I implement the try/except statement, nothings gets rendered at all. Even the first page, which uses a completely different handler. I want to know why and also what's wrong with the try/except statement.
Hope that helps.
class MainPage(webapp2.RequestHandler):
def get(self):
page = env.get_template('main.html')
self.response.out.write(page.render())
class DatabaseHandler(webapp2.RequestHandler):
def get(self):
database = self.request.get('db')
mathPage = env.get_template('mp_database.html')
menuPage = env.get_template('mi_database.html')
if database == 'mathproblem':
self.response.write(mathPage.render())
elif database == 'menuitem':
self.response.write(menuPage.render())
def post(self):
submit = self.request.get('submit')
if submit == 'Submit':
page = env.get_template('mp_database.html')
problem = self.request.get('problem')
problem_db = MathProblem(task=problem)
problem_db.put()
value = {'added': '\(' + problem + '\)' + ' ' 'added'}
self.response.write(page.render(value))
elif submit == 'Check':
page = env.get_template('mp_database.html')
problem = self.request.get('problem')
values = {'displayed': '$$' + problem + '$$',
'problem': problem, 'text': 'Problem'}
self.response.write(page.render(values))
app = webapp2.WSGIApplication([
('/', MainPage),
('/database', DatabaseHandler),
], debug=True)

Filtering and prettyfying the response content of a django http request

The following django middleware function is used to identify active links in a django response object. If a link is active, its marked with a css class and the href attribute gets replaced by javascript:void(null);. Using this function, the last two lines before the return statement are so slow that i cant use it, further, no css, js and images are rendered. However, if i put these two calls into the for loop, everything is fine and fast. But, i dont want these two calls executed for each active link on page, instead i want them executed only once, and that doesnt work, i really cant see why and what the for loop has to do with it. Its no BeautifulSoup issue, because its the same with re.sub('\s+','',response.content) or the replace function. As far as i have investigated this, i can tell you that the very last line before the return statement is the slow one, as long as its not executed inside the for loop. I'm really excited about a possible explanation.
import re
from django_projects.projects.my_project.settings import SITE_NAME
from BeautifulSoup import BeautifulSoup
class PostRender():
def process_response(self, request, response):
link_pattern=re.compile('<a.*href="(http://%s)*%s".*>' % (SITE_NAME,request.path),re.IGNORECASE)
klass_pattern=re.compile('class="[^"]*"',re.IGNORECASE)
href_pattern=re.compile('href="(http://%s)*%s(\?.*)*"' % (SITE_NAME,request.path),re.IGNORECASE)
#find all active links
search=re.finditer(link_pattern ,response.content)
for res in search:
result=res.group()
klassname='class="active"'
if 'class' in result:
klass=re.search(klass_pattern,result).group().split('=')[1]
if len(klass) != 0:
klassname='class="%s %s"' % (klass[1:-1],'active')
link=re.sub(href_pattern,'href="javascript:void(null);"',re.sub(klass_pattern,klassname,result))
response.content=re.sub(result,link,response.content)
soup=BeautifulSoup(response.content)
response.content=soup.prettify()
return response

How do you render the front page of a plone site in python?

The following browser view should return the content of the front page of the first Plone Site in it's context. However, I can not seem to obtain an object which is able to render html content.
from Products.Five import BrowserView
from zope.component import getMultiAdapter
class RenderFirst (BrowserView):
def __call__ (self):
def findPlones (context):
plones = context.objectValues("Plone Site")
folders = context.objectValues("Folder")
folders = set(folders).difference(set(plones))
for folder in folders:
plones += findPlones(folder)
return plones
plones = findPlones(context)
if len(plones):
default_page = plones[0].getDefaultPage()
content = plones[0].unrestrictedTraverse (default_page)
view = getMultiAdapter ((content, self.request))
return view()
else:
return "no plone"
The previous code when run tells me that the object view is not callable.
plones[0] is a Plone Site object and when called produces a KeyError for folder_listing
if I call the content object I get an AttributeError for document_view
There are lots of combinations here, of calling different adapters of different objects. Haven't yet found the right object which can render the page. Anyone know how to do this?
When I try this in a pdb a simple plones[0]() works fine.
Take a look at http://pypi.python.org/pypi/plone.subrequest.

jQuery getJSON Output using Python/Django

So, I'm trying to make a simple call using jQuery .getJSON to my local web server using python/django to serve up its requests. The address being used is:
http://localhost:8000/api/0.1/tonight-mobile.json?callback=jsonp1290277462296
I'm trying to write a simple web view that can access this url and return a JSON packet as the result (worried about actual element values/layout later).
Here's my simple attempt at just alerting/returning the data:
$.getJSON("http://localhost:8000/api/0.1/tonight-mobile.json&callback=?",
function(json){
alert(json);
<!--$.each(json.items, function(i,item){
});-->
});
I am able to access this URL directly, either at http://localhost:8000/api/0.1/tonight-mobile.json or http://localhost:8000/api/0.1/tonight-mobile.json&callback=jsonp1290277462296 and get back a valid JSON packet... So I'm assuming it's in my noob javascript:)
My views.py function that is generating this response looks as follows:
def tonight_mobile(request):
callback = request.GET.get('callback=?', '')
def with_rank(rank, place):
return (rank > 0)
place_data = dict(
Places = [make_mobile_place_dict(request, p) for p in Place.objects.all()]
)
xml_bytes = json.dumps(place_data)
xml_bytes = callback + '(' + xml_bytes + ');'
return HttpResponse(xml_bytes, mimetype="application/json")
With corresponding urls.py configuration:
(r'^tonight-mobile.json','iphone_api.views.tonight_mobile'),
I am still somewhat confused on how to use callbacks, so maybe that is where my issue lies. Note I am able to call directly a 'blah.json' file that is giving me a response, but not through a wired URL. Could someone assist me with some direction?
First, callback = request.GET.get('callback=?', '') won't get you the value of callback.
callback = request.GET.get( 'callback', None )
Works much better.
To debug this kind of thing. You might want to include print statements in your Django view function so you can see what's going on. For example: print repr(request.GET) is a helpful thing to put in a view function so that you can see the GET dictionary.

Categories