Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Tuesday, May 5, 2015

Django Classified App

Great and easy to use scaffolding template for you Classified app made using django
DCF - django classified app

Friday, January 9, 2015

django-constance

A Django app for storing dynamic settings in pluggable backends (Redis and Django model backend built in) with an integration with the Django admin app.

GitHub Repo

Monday, February 24, 2014

Using request.DELETE in django

If you want to access QueryDict parameters, when using request.method == 'DELETE' you can't access it via request.DELETE as when you use GET or POST.

Instead you should create that Dict yourself:

from django.http import QueryDict
<...>
def my_delete_api(request):
if request.method == 'DELETE':
data = QueryDict(request.body)
                key = data.get('key', None)


Wednesday, February 5, 2014

Django 1.7 on the way!

Soon new version of Django will arrive!
https://docs.djangoproject.com/en/dev/releases/1.7/

So if you have old python 2.6 - don't forget to update for 2.7!

So if you use Debian 6 squeeze, you need to update for wheezy!

You can follow that easy manual:
http://www.howtoforge.com/how-to-upgrade-debian-squeeze-to-wheezy

Tuesday, October 1, 2013

Django registration updates

Great project for easy handling user registration in django has updated recently (ok, not actually recently) for django 1.5 support.
If you still do what kind of stuff by hand - take a loot at that helpful project.
django-registration

Friday, September 27, 2013

App Engine 1.8.5 released

Good news!

We’re back with Google App Engine 1.8.5, and this release focuses on an upgrade to the Search API and improvements to the PHP runtime. Next week we’ll be at Zendcon, one of the largest conferences for PHP developers, where we’ll have some cool things to share about the PHP runtime.

https://cloud.google.com/products/app-engine

Thursday, September 26, 2013

OSQA updates for latest Django version

Check out my fork of OSQA project on GitHub.
Now they work with latest Django version 1.5.

OSQA is Open Source Q&A system, created using python (Django), Jquery and other cool tools!

https://github.com/8c1/OSQA

Thursday, February 28, 2013

Django release 1.5 is now available!

Congratulation, version 1.5 of Django Web Framework is now have release status!

In case you have DeprecationWarning:

DeprecationWarning: You have no filters defined on the 'mail_admins' logging handler: adding implicit debug-false-only filter

Update you LOGGING settings for something like that:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}


Improvement of moving from SQLite to MySQL

I want to introduce improvement of my solution switching from SQLite to other DB engine maded by Rune Kaagaard.
Go to the github page.

Tuesday, December 11, 2012

How to create podcast from dropbox folder


  1. Create dropbox account http://db.tt/14Bl8AQ9
  2. Download dropbox client https://www.dropbox.com/downloading
  3. Enable public folder for your account https://www.dropbox.com/enable_public_folder
  4. Put folders with mp3 in to Dropbox Public
  5. Put podcast.py inside Dropbox Public folder
  6. Right click on podcast.py - Dropbox - Copy public link
  7. Paste link to somethere and copy you id https://dl.dropbox.com/u/1234567/podcast.py (1234567 in example)
  8. Edit podcast.py and replace 1234567 with you ID
  9. Run python podcast.py
  10. Copy public link to feed.xml (Right click - Dropbox - Copy public link)
  11. Enter link from clipboard to your favourite podcast player (btw, i greatly recommend you awesome Downcast app for IOS).
  12. Enjoy!

Monday, November 26, 2012

Dealing with unicode user name in OSQA

OSQA is a pretty engine for creating Q&A site for in you community.

I use it for a couple of weeks and i'm very happy with it.
But some day ago i start receiving letter from my user in that they say that it is a bug on site, and user cannot fill additional field in user profile.
After investigation i found a bug.
The root of problem was unicode username.

Link for user settings contain slug field and look like:
url(r'^%s(?P<id>\d+)/(?P<slug>.*)/%s$' % (_('users/'), _('edit/')), app.users.edit_user, name='edit_user'),
and in actual form url it look like
<form name="" action="/users/1/admin/edit/" method="post">
but when you user have unicode user name it look like:
<form name="" action="/users/21//edit/" method="post">
and when user with unicode username try to submit form system do redirect 302 instead of saving data redirect them to correct url for editing (but url in form still same wrong).

i look to the template for edit preference page(forum\skins\default\templates\users\edit.html:36):

<form name="" action="{% url edit_user user.id user.username|slugify %}" method="post">

so template filter slugify does not work with unicode :(

So i created new one :)

in file forum\templatetags\extra_filters.py i add new tag

from django.utils.encoding import smart_unicode
from django.template.defaultfilters import slugify
@register.filter
def slug(value):
    return slugify(smart_unicode(value))
and use them instead |slugify 
i add 
{% load extra_filters %}
in top of template and change filter in form action link:
<form name="" action="{% url edit_user user.id user.username|slug %}" method="post">

And now my users are happy :)




Monday, October 22, 2012

Redirect all request to specific site to new location with appengine

Let say you have web site with complex structure, what stop work for some reason, and you want redirect all request for you site to new location, instead of showing 404 error.

Example:

http://www.oldsite.com/about.html -> http://www.newsite.com/temporarily.html 
http://www.oldsite.com/product.php?id=12 -> http://www.newsite.com/temporarily.html 
http://oldsite.com/product.php?id=12 -> http://www.newsite.com/temporarily.html 
http://oldsite.com/group.php?id=12 -> http://www.newsite.com/temporarily.html

Make what with Google AppEngine. It's free and simple.

  1. You need to create an application on Google Appengine Platform
  2. Now you have http://YOU-APP-ID.appspot.com page where you place handler for you request
  3. For accessing to you app by you custom domain name (www.oldsite.com) instead YOU-APP-ID.appspot.com you need prove you right for what name and add what name in Domain Setup part of YOU-APP-ID application settings page.
  4. Add CNAME record www in DNS settings for oldsite.com and point it to "ghs.googlehosted.com."
  5. Now you need to create and deploy app for handling requests:
    1. Download actual version o Google App Engine SDK for Python
    2. Install SDK and create new app with YOU-APP-ID as application ID
    3. Edit file app.yaml:

    4. application: YOU-APP-ID
      version: 1
      runtime: python
      api_version: 1
      
      handlers:
      - url: .*
        script: main.py
    5. Add main.py:
      from google.appengine.ext import webapp
      from google.appengine.ext.webapp import util
      
      class Redirect (webapp.RequestHandler):
          def get(self):
              self.redirect('http://www.newsite.com/temporarily.html', permanent=True)
                  
      def main():
          application = webapp.WSGIApplication([
              ('/.*', Redirect)
              ],debug=True)
          util.run_wsgi_app(application)
      if __name__ == '__main__':
          main()
      
    6. Deploy app to Google
  6. Now you app redirect all request from www.oldsite.com/anything  to http://www.newsite.com/temporarily.html.
  7. In addition we need to redirect all non www request to request with www, sadly you can not do that redirect only by dns server, you need some magic on http server. In Lighttpd i solve what with adding in conf file:
    $HTTP["host"] =~ "^oldsite\.com$" { url.redirect = ( "^/(.*)" => "http://www.oldsite.com/$1" ) }

Done!

Friday, October 19, 2012

[solved] Move django from SQLite to MySQL

When you start develop new site, you may run from little one with tiny database.
For django best start from sqlite and after some time, if you project begin grow you move to more serious database engine (MySQL, Postgre SQL etc).
Sadly, django does not have any ready tools to move from one to another database.
You may try

  • python ./manage.py dumpdata > data.json

and

  • python ./manage.py loaddata data.json

but unfortunately this doesn't work because of integrity errors...or many other issues

For move from one db to another i follow steps:
  1. Edit settings.py 
    1. add new database in DATABASES settings with 'slave' name like:
      DATABASES = {'default': {...}, 'slave': {...}}
      
    2. if you use apps like south - comment them for a while
  2. Create new db (django create only new file for sqlite database type)
  3. Create tables in new db
    1. python ./manage.py syncdb --database slave
    2. enable south and repeat 3.1
  4. Create file to_slave.py in main project directory:
    • from django.contrib.contenttypes.models import ContentType
      
      def run():
      
       def do(Table):
        if Table is not None:
         table_objects = Table.objects.all()
         for i in table_objects:
          i.save(using='slave')
       
       ContentType.objects.using('slave').all().delete()
      
       for i in ContentType.objects.all():
        do(i.model_class())
      
  5. If you have any kind of signals for you models - disable them before next step
  6. run 
    1. python ./manage.py shell and type command in shell
      1. from to_slave import run
      2. run()
  7. Make 'slave' default database in you project
  8. Done






Sunday, September 23, 2012

Check if field is changed before saving entry


When you save entry in Django, how to check, if a field is changed?
Here is simple solution:
class MyModel(models.Model):
    title = models.CharField(max_length=1)

    def save(self, *args, **kw):
        if self.pk is not None:
            orig = MyModel.objects.get(pk=self.pk)
            if orig.title != self.title:
                print 'title is changed'
        super(MyModel, self).save(*args, **kw)

Friday, July 6, 2012

[fixed] How to load initial data to you django app model


If you need to have some data in you django app when you distribute it to someone else you need to do following steps.
Suppose you have app named weather and a model in that app called City
  1. Create folder fixtures in weather directory
  2. run following comand form project main directory:
python manage.py dumpdata weather.City > "weather\fixtures\initial_data.json"
  1. Whats all
Next time you run:
python manage.py syncdb
you data will be loaded to you app model
Lean more about initial data on django official page 

Tuesday, June 26, 2012

[Fixed] multisite caching on django

When you work with multisite on django you need to do some chaching tricks for optimize perfomance of you sites. Typically you use cache middleware and have no problem for one site

    MIDDLEWARE_CLASSES = [
        'django.middleware.cache.UpdateCacheMiddleware',
        ...
        'django.middleware.cache.FetchFromCacheMiddleware'
    ]
But for many sites you can't use it from the box (otherwise you get equal page for east.mycorp.com/contact.html and west.mycorp.com/contact.html). Trick is simple, you need to do some changes in cache middleware, placed in path to you django installation>/django/middleware/cache.py You need overwrite two function:
  • get_cache_key
  • learn_cache_key
Becasuse basicly django use request.get_full_path() for build cache_key, and when you deal with multisite you get the same result for east.mycorp.com/contact.html and west.mycorp.com/contact.html. We change get_full_path to build_absolute_uri So we put function:
  • _generate_cache_header_key
  • _generate_cache_key
  • get_cache_key - unchanged
  • learn_cache_key - unchanged
from /django/utils/cache.py to our new code in cache.py:
from django.conf import settings
from django.core.cache import get_cache, DEFAULT_CACHE_ALIAS
from django.utils.cache import patch_response_headers, get_max_age, _i18n_cache_key_suffix
from django.utils.hashcompat import md5_constructor
from django.utils.encoding import iri_to_uri

import re
cc_delim_re = re.compile(r'\s*,\s*')

# custom function for Multisiting
def _generate_cache_header_key(key_prefix, request):
    """Returns a cache key for the header cache."""
    #path = md5_constructor(iri_to_uri(request.get_full_path()))
    path = md5_constructor(iri_to_uri(request.build_absolute_uri())) # patch using full path
    cache_key = 'views.decorators.cache.cache_header.%s.%s' % (
        key_prefix, path.hexdigest())
    return _i18n_cache_key_suffix(request, cache_key)

def _generate_cache_key(request, method, headerlist, key_prefix):
    """Returns a cache key from the headers given in the header list."""
    ctx = md5_constructor()
    for header in headerlist:
        value = request.META.get(header, None)
        if value is not None:
            ctx.update(value)
    #path = md5_constructor(iri_to_uri(request.get_full_path()))
    path = md5_constructor(iri_to_uri(request.build_absolute_uri()))
    cache_key = 'views.decorators.cache.cache_page.%s.%s.%s.%s' % (
        key_prefix, request.method, path.hexdigest(), ctx.hexdigest())
    return _i18n_cache_key_suffix(request, cache_key)

def get_cache_key(request, key_prefix=None, method='GET', cache=None):
    """
    Returns a cache key based on the request path and query. It can be used
    in the request phase because it pulls the list of headers to take into
    account from the global path registry and uses those to build a cache key
    to check against.

    If there is no headerlist stored, the page needs to be rebuilt, so this
    function returns None.
    """
    if key_prefix is None:
        key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
    cache_key = _generate_cache_header_key(key_prefix, request)
    if cache is None:
        cache = get_cache(settings.CACHE_MIDDLEWARE_ALIAS)
    headerlist = cache.get(cache_key, None)
    if headerlist is not None:
        return _generate_cache_key(request, method, headerlist, key_prefix)
    else:
        return None

def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None):
    """
    Learns what headers to take into account for some request path from the
    response object. It stores those headers in a global path registry so that
    later access to that path will know what headers to take into account
    without building the response object itself. The headers are named in the
    Vary header of the response, but we want to prevent response generation.

    The list of headers to use for cache key generation is stored in the same
    cache as the pages themselves. If the cache ages some data out of the
    cache, this just means that we have to build the response once to get at
    the Vary header and so at the list of headers to use for the cache key.
    """
    if key_prefix is None:
        key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
    if cache_timeout is None:
        cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
    cache_key = _generate_cache_header_key(key_prefix, request)
    if cache is None:
        cache = get_cache(settings.CACHE_MIDDLEWARE_ALIAS)
    if response.has_header('Vary'):
        headerlist = ['HTTP_'+header.upper().replace('-', '_')
                      for header in cc_delim_re.split(response['Vary'])]
        cache.set(cache_key, headerlist, cache_timeout)
        return _generate_cache_key(request, request.method, headerlist, key_prefix)
    else:
        # if there is no Vary header, we still need a cache key
        # for the request.get_full_path()
        cache.set(cache_key, [], cache_timeout)
        return _generate_cache_key(request, request.method, [], key_prefix)

And save it to the new folder SiteCache in your django project directory. Now add to settings.py:
MIDDLEWARE_CLASSES = (
    'SiteCache.cache.UpdateCacheMiddleware',
    ...
    'SiteCache.cache.FetchFromCacheMiddleware',
)
Congratulations, now request to cached page east.mycorp.com/contact.html and west.mycorp.com/contact.html return proper results!

Monday, June 25, 2012

How to entirely clear django cache

Some time you need for developer purposes entirely clear django cache, to do it use that simple code:
from django.core.cache import cache
cache.clear()

Monday, June 18, 2012

How to move beyond the App Engine free mail limitations

Appengine have very tough quota limits for sending mail to user (now it's about 100 recipients in day). It so small even for little apps. What you need to do for solve that kind of problem?
  1. Use you standalone server or VPS with installed php
  2. Create file mailgate.php which contain code below and upload file to you VPS.:
    ≶?php
     $MAILGATE_KEY = 'MYSUPERSECRETCODEPHRASE';
     $user_code  = $_POST['code'];
     if ($user_code != $MAILGATE_KEY) {echo("wrong pass");die();}
     $to   = $_POST['to'];
     $subject  = $_POST['subj'];
     $body   = $_POST['body'];
     $headers = 'From: MY NAME ' . "\r\n" .
     'Reply-To:  myemail@example.com' . "\r\n".
        'Content-type: text/plain; charset=utf-8' . "\r\n";
     if (mail($to, $subject, $body, $headers)) {echo("sent");} else {echo('error');die();}
    ?>
    
  3. on server side create function for easy sending mail
    def sendmail(to, subject, body):
        mailqueue = taskqueue.Queue('mailqueue')
        
        task = taskqueue.Task(url='/queue/sendmail', params={
                                                    'subject': subject,
                                                    'to': to,
                                                    'body': body})
        mailqueue.add(task)
    
  4. create file queue.yaml for properly sending mail (appengine limit count of request per minutes)
    queue:
    - name: mailqueue
      bucket_size: 1
      rate: 30/m
      retry_parameters:
        task_age_limit: 2d
    
  5. Create entry point '/queue/sendmail':
    class SendEmail(webapp.RequestHandler):
        def post(self):
            data = {
                'to':  unicode(self.request.get('to')).encode('utf-8'), 
                'subj': unicode(self.request.get('subject')).encode('utf-8'),
                'body': unicode(self.request.get('body')).encode('utf-8'),
                'code': settings.MAILGATE_KEY
                }
            data = urllib.urlencode(data)
            result = urlfetch.fetch(settings.MAILGATE_URL, deadline=55, payload = data, method = urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'})
            logging.info("Sending mail to " + self.request.get('to') + " " + result.content)
    
  6. Put in you settings.py file with definition for:
    • MAILGATE_URL (it's full URL where you you actual mailgate.php available)
    • MAILGATE_KEY (same as in mailgate.php)
  7. Use you custome sendmail instead of appengine default.
  8. Enjoy!

Thursday, September 22, 2011

Delete entry of Table Entry

To delete all entry for specific Model on Google App Engine use following code:
from google.appengine.ext import db
class Entry(db.Model):
    pass
db.delete(Entry.all().fetch(1000))