Showing posts with label django. Show all posts
Showing posts with label django. Show all posts

Tuesday, November 20, 2012

How to use Flask micro-framework


1
Where does one draw the distinction between micro- and megaframeworks? Or, for that reference, just a "framework"?

2
The difference between a library and a framework is simply that you call the library whereas the framework calls you. The framework provides a frame into which you put your code as opposed to a library which you use as part of your code.
Generally I would consider any framework which requires (almost) no setup requirements to be a microframework. This is opposed to frameworks which require a basic configuration, directory layout or certain files to be present.
However there are a lot of other people with other definitions regarding this, the distinction is not at all very clear for example there are people that consider being written in a single file to be a distinguishing feature of microframeworks.


3
http://hitesh.in/2012/how-to-migrate-from-bottle-py-to-flask-micro-framework/

from flask import Flask, render_template as template, request, make_response, jsonify, abort from flask.ext.sqlalchemy import SQLAlchemy

from bottle import route, run, template, install, static_file, response import bottle



What is the g object in Flask?







Sunday, November 11, 2012

streaming-a-csv-file-in-django , stream-an-httpresponse-with-django



django return response large

1
Send large files through Django, and how to generate Zip files
http://djangosnippets.org/snippets/365/



2
django stream file in response
http://stackoverflow.com/questions/5146539/streaming-a-csv-file-in-django
MAIN CSV in-memory file csv writer.



3
Piston is a relatively small Django application that lets you
create application programming interfaces (API) for your sites.
https://bitbucket.org/jespern/django-piston/wiki/Home
https://bitbucket.org/jespern/django-piston/src/c4b2d21db51a/piston/middleware.py




4
http://stackoverflow.com/questions/2922874/how-to-stream-an-httpresponse-with-django
from django.views.decorators.http import condition

@condition(etag_func=None)
def stream_response(request):
    resp = HttpResponse( stream_response_generator(), mimetype='text/html')
    return resp

def stream_response_generator():
    yield "<html><body>\n"
    for x in range(1,11):
        yield "<div>%s</div>\n" % x
        yield " " * 1024  # Encourage browser to render incrementally
        time.sleep(1)
    yield "</body></html>\n"

Saturday, November 3, 2012

Thursday, October 25, 2012

HTML evil tags sanitizing with Python: Bleach is the best library!

Google Search:
html sanitizer for python





>>> import bleach
>>> print bleach.linkify('an http://example.com url')
an <a href="http://example.com" rel="nofollow">http://example.com</a> url
>>> print bleach.linkify('<a href="http://example.com" rel="nofollow">http://example.com</a>')
<a href="http://example.com" rel="nofollow">http://example.com</a>
>>> print bleach.linkify('an <a href="http://example.com" rel="nofollow">http://example.com</a> url')
an <a href="http://example.com" rel="nofollow">http://example.com</a> url
>>>


It's smart enough not to 'double linkify' it.

https://github.com/jsocol/bleach
http://bleach.readthedocs.org/en/latest/goals.html
http://coffeeonthekeyboard.com/bleach-html-sanitizer-and-auto-linker-for-django-344/




Basic Use

The simplest way to use Bleach is:
>>> import bleach

>>> bleach.clean('an <script>evil()</script> example')
u'an &lt;script&gt;evil()&lt;/script&gt; example'

>>> bleach.linkify('an http://example.com url')
u'an <a href="http://example.com" rel="nofollow">http://example.com</a> url
NB: Bleach always returns a unicode object, whether you give it a bytestring or a unicode object, but Bleach does not attempt to detect incoming character encodings, and will assume UTF-8. If you are using a different character encoding, you should convert from a bytestring to unicode before passing the text to Bleach.













Tuesday, October 2, 2012

django how to remove error from form field?

django how to remove error from form field?

http://blog.mathieu-leplatre.info/remove-django-form-field-valiation-errors-manually.html


Remove django form field validation errors manually



Original post at Makina Corpus
Sometimes I look for something which seems so simple and stupid that I can't imagine it does not exist. It makes me wonder why and who is the fool. Worse, I can't be sure about my search keywords to prove me anything.
I just wanted to delete, reset or remove the validation errors of a single form field, within a django view, without overriding the form or field class.

A one-liner

aform.errors['afield'] = aform['afield'].error_class()
That's it folks !
  • This will not affect other fields errors or non-field errors ;
  • This will reuse nicely the field error class (ErrorDict or ErrorList) ;
  • You cannot set aform.errors['afield'] = None or your form full_clean() will be performed again !
  • Obviously, the ideal approach is to override your form clean() properly.

Tue 06 December 2011
By Mathieu Leplatre
In Dev.
tags: djangotips




Monday, September 24, 2012

How Django Sessions work - diagrams


How Django Sessions work - diagrams
http://eli.thegreenplace.net/2011/06/29/django-sessions-part-ii-how-sessions-work/



https://docs.djangoproject.com/en/1.4/topics/http/sessions/

Clearing the session table

If you're using the database backend, note that session data can accumulate in the django_session database table and Django does not provide automatic purging. Therefore, it's your job to purge expired sessions on a regular basis.
To understand this problem, consider what happens when a user uses a session. When a user logs in, Django adds a row to the django_session database table. Django updates this row each time the session data changes. If the user logs out manually, Django deletes the row. But if the user does not log out, the row never gets deleted.
Django provides a sample clean-up script: django-admin.py cleanup. That script deletes any session in the session table whose expire_date is in the past -- but your application may have different requirements.




Thursday, September 20, 2012

Tuesday, September 18, 2012

Request.Session django



ASDF {{ request.session }} <br />
<ul>
{% for k,v in request.session.items %}
<li>{{ k }} |value={{ v }}</li>
{% endfor %}
</ul>



######################
ASDF <django.contrib.sessions.backends.cache.SessionStore object at 0x24ddc90>

  • customer |value=willa01
  • _auth_user_id |value=11
  • _auth_user_backend |value=safeavenue.util.auth.IframeAuthBackend
  • token |value=a03ff6c580
  • operator |value=gtn
  • cookie_path |value=/iframe/gtn/cs/willa01/a03ff6c580/



##########################

request.session.session_key

ASDF {{ request.session.session_key }} <br />

This works.

request.session.items IS DIFFERENT from request.session.session_key.
and the latter is accessible in the TEMPLATE (after session middleware->process_response.

in
C:\Python26\Lib\site-packages\django\contrib\sessions\middleware.py

Line 38:

                response.set_cookie(settings.SESSION_COOKIE_NAME,
                        request.session.session_key, max_age=max_age,



OBJECTIVE: You wanted to get the session key in the template, so that you can set it using jQuery plugin,
because IE7 couldn't set it for an iframed page.



#############################
The below snippet doesn't work in the view.py code, as the process_response session middleware has not yet been invoked.


##        session_key = request.COOKIES[p3p.SESSION_COOKIE_NAME]
        print "zzz", request.COOKIES
        for key in request.COOKIES:
            print "aaa", request.COOKIES.get(key)
##        print "session_key", session_key
        print "End"


The result: it prints a lot of Nothing.









Wednesday, September 12, 2012

Django snippets site is a webapp: About



About this site

What is this?

This site grew out of a need to scratch an itch. The Django community is incredibly friendly and helpful, and more than willing to share useful bits of code, but there had never been a place to do that easily. There's a "cookbook" section on the Django wiki, but by its nature that's hard to keep organized – every time someone adds something they have to remember to go back and update one or more pages which list the bits of code posted there. And lots of people post things on their blogs, but again it's hard to organize that because you need to maintain a huge list of bookmarks and lists of blogs.
I knew there was a "snippets" application built with Ruby on Rails, and that a couple of communities were using it (for example), and figured it wouldn't be too hard to build something similar with Django. So I sat down one Saturday afternoon, and by that evening I had most of the code. Then, at PyCon 2007, I showed the site around and finally launched it.

What was that about code?

This site is as open-source as reasonably possible. The bulk of the functionality is in a single application I've called "Cab" (named for Cab Calloway, whose "scat" style seemed a good fit for a site featuring lots of snippets of code), and is available under a BSD license; the source is hosted as a Google Code project a Github repo if you'd like to go play with or use it.
The user-registration code is also available, as a separate application.

I have more questions!

Check out the FAQ, and hopefully I've answered them there :)






















Advanced Search
Latest snippets:









About

Powered by Django.
Learn more about this site.
Read the FAQ.















Django Snippets: how to set p3p header in python


how to set p3p header in python

https://github.com/jjanssen/django-p3p
Django P3P makes it easier to set P3P HTTP headers to prevent session loss. — Read more
2 months ago

http://djangosnippets.org/snippets/786/

P3P Headers for iframes

1
2
3
4
def index(request):
    response = render_to_response('mytemplate.html')
    response["P3P"] = 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'
    return response








More like this

  1. Compact P3P policy header injection middleware by mwolgemuth 3 years, 11 months ago
  2. Avoid IE Brokenness When using Vary and Attachments by axiak 5 years, 5 months ago
  3. Extended db cache backend with 'filter() / LIKE' support (and now scheduled cache clean!) by sleepycal 2 years, 8 months ago
  4. Internet Explorer Redirect Decorator by johnboxall 3 years, 11 months ago
  5. Foreign Key list_filter wthout custom FilterSpec by haileris23 2 years, 7 months ago


http://djangosnippets.org/snippets/1084/

Compact P3P policy header injection middleware

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
P3P_COMPACT = 'some string' # I import this from a global constants file
# eg. P3P_COMPACT='CP="CAO DSP CURa ADMa DEVa TAIa CONa OUR DELa BUS IND PHY ONL UNI PUR COM NAV DEM STA"'

class MiddlewareResponseInjectP3P(object):
    def __init__(self):
        self.process_response = self.inject

    def inject(self, request, response):
        response['P3P'] = P3P_COMPACT
        return response
















p3p header problem


p3p header problem - Google Search

http://stackoverflow.com/questions/999534/ie-p3p-iframe-and-blocked-cookies-works-until-page-host-page-has-personal-inf

This probably won't help anyone else, but I was banging my head against the wall for weeks over this one. It turns out that IE 7 won't allow 3rd-party cookies to be set, even with a valid P3P compact policy if the HTML meta tag for Content-Type has a different character set declaration on the page with the iframe from the page within the iframe.


p3p header workaround - Google Search

http://www.nikcub.com/posts/facebook-also-doesnt-honor-p3p


Facebook and many other sites also bypass Internet Explorer privacy controls

 #
There is a post today on a Microsoft MSDN blog about how Google bypasses third-party cookie control in Internet Explorer by setting a false P3P header. The post author is Dean Hachamovitch, who is the VP for IE, and follows up from a big story last week about how Google and a number of other ad networks are bypassing third-party cookie blocking in Safari by using a workaround (the workaround involves an IFRAME and a form that is submitted automatically using Javascript).
The case with IE is different. Google (and many other sites) are taking advantage of the P3P protocol (a privacy extension to HTTP) to set third-party cookies. Here is a summary of what Google is doing, from the article:
By default, IE blocks third-party cookies unless the site presents a P3P Compact Policy Statement indicating how the site will use the cookie and that the site’s use does not include tracking the user.
Here is what a valid P3P header looks like, as set by microsoft.com:
$ nc microsoft.com 80
HEAD / HTTP/1.1
Host: www.microsoft.com

HTTP/1.1 301 Moved Permanently
Connection: close
Date: Tue, 21 Feb 2012 04:29:06 GMT
Server: Microsoft-IIS/6.0
P3P: CP='ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI'
X-UA-Compatible: IE=EmulateIE7
X-Powered-By: ASP.NET
Location: http://www.microsoft.com
Content-Length: 23
Content-Type: text/html
Cache-control: private
If an invalid P3P header is set, or a header that doesn't state policy, Internet Explorer will by default accept the third-party cookies (this doesn't happen in IE9). This is what the P3P header looks like for google.com:
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
Not mentioned in the Microsoft article is that Facebook are also setting an invalid header ('invalid' may not be the right terminology here, but they are setting a header that does not contain valid privacy policies). This results in Internet Explorer (pre version 9) accepting the third-party cookies.
From facebook.com:
$ nc facebook.com 80
GET / HTTP/1.1
Host: www.facebook.com

HTTP/1.1 302 Found
Location: http://www.facebook.com/common/browser.php
P3P: CP="Facebook does not have a P3P policy. Learn why here: http://fb.me/p3p"
Set-Cookie: datr=FxdDTzq9li7A7DRTAxVSXaZN; expires=Thu, 20-Feb-2014 04:01:27 GMT; path=/; domain=.facebook.com; httponly
Content-Type: text/html; charset=utf-8
X-FB-Debug: 8V3X/HiIi+1PrEZFy4c8LpavYxpBvnsojJ+pcYyGJUg=
X-Cnection: close
Date: Tue, 21 Feb 2012 04:01:27 GMT
Content-Length: 0
The reason Facebook gives for this header in the page that is linked from it is:
The organization that established P3P, the World Wide Web Consortium, suspended its work on this standard several years ago because most modern web browsers do not fully support P3P. As a result, the P3P standard is now out of date and does not reflect technologies that are currently in use on the web, so most websites currently do not have P3P policies.
Microsoft explicitly called out Google for their behaviour but either neglected to mention or didn't investigate Facebook (skeptics may believe that this is because of Microsoft's shareholding in Facebook and their partnerships in search and advertising (HT ask4n)).



http://stackoverflow.com/questions/tagged/p3p


Will IE6 Send Third-Party Cookie for Page Without P3P Header

Here is the situation, A page with exist cookie, has been placed in iframe. For IE6, will it send the cookie content if the page does not have p3p header? I know IE (in default setting) will stop ...



3rd Party Cookies, What's wrong with this scenario

I've hit a wall of frustration while dealing with a 3rd party payment processor. They claim to be reputable but we can't work past this issue. They've instructed our client to simply display a large ...


















write django middleware


write django middleware - Google Search

https://docs.djangoproject.com/en/dev/topics/http/middleware/


Writing your own middleware

Writing your own middleware is easy. Each middleware component is a single Python class that defines one or more of the following methods:

process_request

process_request(selfrequest)
request is an HttpRequest object. This method is called on each request, before Django decides which view to execute.
process_request() should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other middleware and, then, the appropriate view. If it returns an HttpResponse object, Django won't bother calling ANY other request, view or exception middleware, or the appropriate view; it'll return that HttpResponse. Response middleware is always called on every response.

process_view

process_view(selfrequestview_funcview_argsview_kwargs)
request is an HttpRequest object. view_func is the Python function that Django is about to use. (It's the actual function object, not the name of the function as a string.) view_args is a list of positional arguments that will be passed to the view, and view_kwargs is a dictionary of keyword arguments that will be passed to the view. Neither view_args nor view_kwargsinclude the first view argument (request).
process_view() is called just before Django calls the view. It should return either None or an HttpResponse object. If it returnsNone, Django will continue processing this request, executing any other process_view() middleware and, then, the appropriate view.



https://docs.djangoproject.com/en/dev/ref/middleware/


Middleware

This document explains all middleware components that come with Django. For information on how to use them and how to write your own middleware, see the middleware usage guide.

Available middleware

Cache middleware

class UpdateCacheMiddleware
class FetchFromCacheMiddleware
Enable the site-wide cache. If these are enabled, each Django-powered page will be cached for as long as theCACHE_MIDDLEWARE_SECONDS setting defines. See the cache documentation.

“Common” middleware

class CommonMiddleware
Adds a few conveniences for perfectionists:





http://www.djangobook.com/en/beta/chapter16/

You're reading an outdated version of this book; a newer version is available.

Chapter 16: Middleware





how can django detect user agent


how can django detect user agent - Google Search

http://stackoverflow.com/questions/2669294/how-to-detect-browser-type-in-django


You can extract that information from the request object like so:
request.META['HTTP_USER_AGENT']



http://stackoverflow.com/questions/164427/change-django-templates-based-on-user-agent

Rather than changing the template directories dynamically you could modify the request and add a value that lets your view know if the user is on an iphone or not. Then wrap render_to_response (or whatever you are using for creating HttpResponse objects) to grab the iphone version of the template instead of the standard html version if they are using an iphone.








Tuesday, September 4, 2012

Install Django on Debian6 (preparing for LousyOperator)


http://library.linode.com/frameworks/django-apache-mod-wsgi/debian-6-squeeze


Configure Django Applications for WSGI

In order for mod_wsgi to be able to provide access to your Django application, you will need to create a django.wsgi file inside of your application directory. For the purposes of this example, we assume that your application will be located outside of your DocumentRoot in the directory /srv/www/ducklington.org/application. Modify this example and all following examples to conform to the actual files and locations used in your deployment.
File:/srv/www/ducklington.org/application/django.wsgi
import os
import sys

sys.path.append('/srv/www/ducklington.org/application')

os.environ['PYTHON_EGG_CACHE'] = '/srv/www/ducklington.org/.python-egg'
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
You must append the path of your application to the system path as above. Additionally, declaration of the PYTHON_EGG_CACHE variable is optional but may be required for some applications when WSGI scripts are executed with the permissions of the web server. Finally, the DJANGO_SETTINGS_MODULE must refer to the Django settings.py file for your project. You will need to restart Apache after modifying the django.wsgi file.








Iframe problems in django project?

Iframe doesn't show in lousyoperator/mockportal?


1.
Clear all cookies.
session cookies, csrf cookies,
from the LousyOperator and also the Iframe.
=If not, the error is that 'alluserdata' javascript does not show up, AJAX call fails
(you don't see the product and device list) if you didn't clear the cookies.

2.
Accept the 'invalid SSL certificate' (in Chrome, and also Firefox)
then only the Iframe will show up in the tag (else, error 503 unknown error will show in the browser.)
= The actual site, will have an actual SSL certificate, and won't have this problem.







Thursday, August 30, 2012

django and cookies

Is it possible to set the django csrf cookie to be http-only? Alike to SESSION_COOKIE_HTTPONLY with session cookie, but for the csrf one?
http://stackoverflow.com/questions/10861784/django-csrf-cookie-httponly


I tried the second method and it works wonderfully, thanks! Just added the middleware before csrf (obvious but it took me a while as I put it after) and put CSRF_COOKIE_NAME in settings and that's all. – Mark Jun 2 at 21:08

Currently there is not setting option for this.
You could override the process_response() method ofdjango.middleware.csrf.CsrfViewMiddleware and using the customized one instead ofCsrfViewMiddleware in MIDDLEWARE_CLASSES
class Foo(CsrfViewMiddleware):
    def process_response(self, request, response):
        response = super(CsrfViewMiddleware, self).process_response(request, response)
        response.cookies[settings.CSRF_COOKIE_NAME]['httponly'] = True
        return response
Or in another middleware which is invoked after CsrfViewMiddleware in response
class Foo(object):
    def process_response(self, request, response):
        if settings.CSRF_COOKIE_NAME in response.cookies:
            response.cookies[settings.CSRF_COOKIE_NAME]['httponly'] = True
        return response


I'm not going to categorize as a bug, because over HTTPS we also have strict referer checking for CSRF protection, so leaking of the token is not a critical issue.







http://eli.thegreenplace.net/2011/06/24/django-sessions-part-i-cookies/

http://coffeeonthekeyboard.com/tag/django-nyc-security/page/2/





a-custom-login-page/
http://solutoire.com/2009/02/26/django-series-1-a-custom-login-page/
http://www.alandelevie.com/2008/12/14/a-simple-introduction-to-django-forms/






template-response/
https://docs.djangoproject.com/en/dev/ref/template-response/
https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.Context
https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.RequestContext






http://stackoverflow.com/questions/5037505/web-application-best-way-to-handle-state


I have some crud pages for which I have to store some state information, like current page, records per page, current order, filter conditions, and sometimes way more information...
I'd like to use friendly urls similar to rest style, something like http://microformats.org/wiki/rest/urls (GET for browsing, POST to add, PUT to edit, DELETE to remove)
The problem with cookies is that if I open several tabs, all of them would share the same cookies, it's the same with the session because the session id is stored in a cookie
if I try to keep those params in the url (something like GET /clients?page=1&len=10&sort=name&filter=smith) as soon as I issue a POST I loose those values
the other solution would be to store the state on hidden inputs, and to always issue posts carrying around those hidden inputs, but in that case I can't use GET for queries...
so, how do you handle web presentation state???