Login

Snippets by limodou

Snippet List

staticview for app

This module is comes from the original staticview.py from django. But when you using it, it can looks for static files in your app's subdirectory. So that you can put static files which concerned with your app in a subdirectory of the app. I should say it method only suit for developing, so if you want to deploy your application to apache, you should copy static folder to the real media folder. And if you keep the same structure of the directory, then it'll be very easy. And you can write a little script to automatically do that. But for now, I didn't have written one yet :P How to use it in urls.py -------------------------- Here's an example: (r'^site_media/(.*)$', 'utils.staticview.serve', {'document_root': settings.SITE_MEDIA, 'app_media_folder':'media'}), It seems just like the original one in django. But there is a new parameter "app_media_folder", it's used for subdirectory name of app. So your django project folder structure maybe seem like this: /yourproject /apps /appone /media /css /img /js /media /css /img /js

  • static
Read More

Url filter middleware

How to config it ------------------ You can treat it as a micro url filter framework. Before you using it, you should setup some options about it. The option entry shoud be like this: FILTERS = ( (r'^user/(?P<user_id>\d+)/', 'apps.users.filter.check_valid_user'), ) FILTERS should be a list or tuple with two elements tuple item. The format should be like: (url_patterns, function) And url_patterns could be a single regex expression or a list/tuple regex expressions, So you can set multi regex expression in it. And the regulation is just like url dispatch, as above example, the url pattern is: r'^user/(?P<user_id>\d+)/' So you can see, you can set parameter name `user_id`, then it'll be passed to the function behind. Function can be a string format, just like above example, and it can be also a real function object. It'll only impact request. How to write filter function ------------------------------- According above example, I define a url pattern, and what to check if the user is a valid user, and if the user is visiting his own urls, so the filter function could be: from django.contrib.auth.models import User from utils.common import render_template def check_valid_user(request, user_id): if request.user.is_anonymous(): return render_template(request, 'users/user_login.html', {'next':'%s' % request.path}) try: person = User.objects.get(pk=int(user_id)) except User.DoesNotExist: return render_template(request, 'error.html', {'message':_("User ID (%s) is not existed!") % user_id}) if person.id != request.user.id: return render_template(request, 'error.html', {'message':_('You have no right to view the page!')}) I think the code is very clear. And you can use it filtermiddleware to do like user authentication check, and other checking for url. BTW, render_template is comes from [Snippets #4](http://www.djangosnippets.org/snippets/4/)

  • middleware
  • filter
  • url
Read More

Format transition middleware

Note: This is a testing middleware. This snippets may be changed frequently later. What's it ----------- Sometimes I thought thow to easy the output data into another format, except html format. One way, you can use decorator, just like: @render_template(template='xxx') def viewfunc(request,...): And the output data of viewfunc should be pure data. And if want to output json format, you should change the decorator to: @json_response def viewfunc(request,...): I think it's not difficult. But if we can make it easier? Of cause, using middleware. So you can see the code of `process_response`, it'll judge the response object first, if it's an instance of HttpResponse, then directly return it. If it's not, then get the format of requst, if it's `json` format, then use json_response() to render the result. How to setup `request.format`? In `process_request` you and see, if the `request.REQUEST` has a `format` (you can setup it in settings.py with FORMAT_STRING option), then the `request.format` will be set as it. If there is not a such key, then the default will be `json`. So in your view code, you can just return a python variable, this middleware will automatically render this python variable into json format data and return. For 0.2 it support xml-rpc. But it's very different from common implementation. For server url, you just need put the same url as the normal url, for example: http://localhost:8000/booklist/ajax_list/?format=xmlrpc Notice that the format is 'xmlrpc'. A text client program is: from xmlrpclib import ServerProxy server = ServerProxy("http://localhost:8000/booklist/ajax_list/?format=xmlrpc", verbose=True) print server.booklist({'name':'limodou'}) And the method 'booklist' of server is useless, because the url has include the really view function, so you can use any name after `server`. And for parameters of the method, you should use a dict, and this dict will automatically convert into request.POST item. For above example, `{'name':'limodou'}`, you can visit it via `request.POST['name']` . For `html` format, you can register a `format_processor` callable object in `request` object. And middleware will use this callable object if the format is `html`. Intall --------- Because the view function may return non-HttpResponse object, so this middleware should be installed at the end of MIDDLEWARE_CLASSES sections, so that the `process_response` of this middleware can be invoked at the first time before others middlewares. And I also think this mechanism can be extended later, for example support xml-rpc, template render later, etc, but I have not implemented them, just a thought. Options --------- FORMAT_STRING used for specify the key name of format variable pair in QUERY_STRING or POST data, if you don't set it in settings.py, default is 'format'. DEFAYLT_FORMAT used for default format, if you don't set it in settings.py, default is 'json'. Reference ----------- Snippets 8 [ajax protocol for data](http://www.djangosnippets.org/snippets/8/) for json_response

  • middleware
  • format
  • json
Read More

Simple profile middleware

Intall -------- In your settings.py, set it in MIDDLEWARE_CLASSES. Default all the profile files will be save in ./profile folder(if there is no this directory, it'll automatically create one), and you can set a PROFILE_DATA_DIR option in settings.py, so that the profile files can be saved in this folder. How does it works ------------------- Record every request in a profile file. As you can see in the code: profname = "%s.prof" % (request.path.strip("/").replace('/', '.')) so if you request an url multi-times, only the last request will be saved, because previous profile files will be overriden. And you can find a commentted line, it'll save each request in different file according the time, so if you like that you can change the code. # profname = "%s.%.3f.prof" % (request.path.strip("/").replace('/', '.'), time.time()) and if you want to see the output, you can run below code, but you should change the filename value: import hotshot, hotshot.stats stats = hotshot.stats.load(filename) #stats.strip_dirs() #stats.sort_stats('time', 'calls') stats.print_stats()

  • middleware
  • profile
Read More

EasyFeed class

This class simplies the Feed class of django. The differences are: 1. Don't need define title and description template file 2. default feed generator class is Atom1Feed 3. According feed_url, EasyFeed can auto get the domain field, and you can also specify the domain parameter.(feed_url should be a full domain path, so you can use [Get the full request path](http://www.djangosnippets.org/snippets/41/) to get the full path of the feed url.) 4. There is a helper function render_feed() to return a response value. example --------- Feed class: class BookCommentsFeed(EasyFeed): def __init__(self, feed_url, book_id): super(BookCommentsFeed, self).__init__(feed_url) self.book_id = book_id self.book = Book.objects.get(id=int(book_id)) def link(self): return '/book/%s' % self.book_id def items(self): return self.book.comment_set.all().order_by('-createtime')[:15] def title(self): return 'Comments of: ' + self.book.title def description(self): return self.book.description def item_link(self, item): return '/book/%s/%s' % (self.book_id, item.chapter.num) def item_description(self, item): return item.content def item_title(self, item): return '#%d Comment for: ' % item.id + item.chapter.title def item_pubdate(self, item): return item.createtime def item_author_name(self, item): return item.username And the view code is: from feeds import * from utils.easyfeed import render_feed from utils.common import get_full_path def bookcomments(request, book_id): return render_feed(BookCommentsFeed(get_full_path(request), book_id))

  • feed
  • rss
Read More

Another pygments for ReST

This is like [snippet 36](/snippets/36/). And it'll return css also. And it's not a filter.If the code parameter is skip, it'll test the code first, and if there is not a suiable lexer for the code, then use default python lexer to render the code. The code lanauage parameter is comes from pygments lexer alias. How to use it ---------------- html = to_html(rest_text) And there is a level parameter in to_html function, default is `2`, it's the sections level. And the html will be `css style + body` How to write ReST --------------------- Below is a example. This is a test. .. code:: def code(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): opt = {'display':'on'} opt.update(options) docnodes.Node(content, ''.join(arguments), **opt) if opt['display'].lower() == 'on': return [nodes.literal_block('', '\n'.join(content))] else: return [] .. code:: html+django <h1 id="title">通讯录</h1> <hr> <div> <table border="0" width="500"> <tr align="right"> <td>{% if has_previous %} <a href="/address?page={{ previous }}">上一页</a> {% endif %} {% if has_next %} <a href="/address?page={{ next }}">下一页</a> {% endif %}</td></tr> </table>

  • pygments
  • rest
Read More

convert plain text to html

Convert plain text to html. For example: text="""aabhttp://www.example.com http://www.example.com http://www.example.com <<< [<aaaa></aaaa>] """ print plaintext2html(text) It can convert url text to html href. And it also can convert space to &nbsp;. So if you paste python code, the indent will not lost at all. Default it'll convert \t to 4 spaces.

  • text
Read More

db_dump.py - for dumpping and loading data from database

Description ============= This tool is used for dump and restore database of Django. And it can also support some simple situations for Model changes, so it can also be used in importing data after the migration of Model. It includes: dump and restore. Dump ====== Command Line: python db_dump.py [-svdh] [--settings] dump [applist] If applist is ignored,then it means that all app will be dumped. applist can be one or more app name. Description of options: * -s Output will displayed in console, default is writing into file * -v Display execution infomation, default is does not display * -d Directory of output, default is datadir in current directory. If the path is not existed, it'll be created automatically. * -h Display help information. * --settings settings model, default is settings.py in current directory. It can only support Python format for now. It'll create a standard python source file, for example: dump = {'table': 'tablename', 'records': [[...]], 'fields': [...]} table' is table name in database, records is all records of the table, it's a list of list, that is each record is a list. fields` is the fields name of the table. Load(Restore) ¶ Command Line: python db_dump.py [-svdrh] [--settings] load [applist] You can refer to the above description for same option. Others is: * -r Does not empty the table as loading the data, default is empty the table first then load the data Using this tool, you can not only restore the database, but also can deal with the simple changes of database. It can select the suitable field from the backup data file according to the changed Model automatically, and it can also deal with the default value define in Model, such as default parameter and auto_now and auto_now_add parameter for Date-like field. And you can even edit the backup data file manually, and add a default key for specify the default value for some fields, the basic format is: 'default':{'fieldname':('type', 'value')} default is a dict, the key will be the field name of the table, the value will be a two element tuple, and the first element of this tuple is type field, the second element is its value. Below is a description of type field: type value description 'value' real value using the value field directly 'reference' referred field name the value of this filed will use the value of referred field. It'll be used when the field name is changed 'date' 'now'|'yyyy-mm-dd' It's a date date type, if the value field is 'now', then the value be current time. Otherwise, it'll be a string, it's format is 'yyyy-mm-dd' 'datetime' 'now'|'yyyy-mm-dd hh:mm:ss' The same as above 'time' 'now'|'hh:mm:ss' The same as above The strategy of selection of default value of a field is: first, create a default value dict according the Model, then update it according the default key of backup data file. So you can see if there is a same definition of a field in both Model and backup data file, it'll use the one in backup data file. According the process of default value, this tool will suport these changes, such as: change of field name, add or remove field name, etc. So you can use this tool to finish some simple update work of database. But I don't give it too much test, and my situation is in sqlite3. So download and test are welcome, and I hope you can give me some improve advices. project site ============= http://code.google.com/p/db-dump/

  • tool
  • dump
Read More

PyIfTag - Just like python if expression

How to use it {% pyif i == 1 %} <p>i=1</p> {% elif i == 3 %} <p>i=3</p> {% else %} <p>other</p> {% endif %} Warning: For now, django don't support elif, so you can use it. And I'v submit a patch about to fix it ( #3090 ). If the patch is accepted, you can use elif tag.

  • tag
Read More

CallTag - Just like include, but can pass parameters to it

I knew that template in myght template system can receive some parameters just like a function. And I also want to implement this function in django template. So I finish a rough one, the code is pasted here. It just like include, but in order to distinguish with "include" tag, I call it "call". So you can use it: {% call "some.html" %} This way just like include tag, and the advanced way: {% call "some.html" with "a" "b"|capfirst title="title1" %} {% call "some.html" with "c" "d" title="title2" %} So you can see, "call" tag can do like a python function, it can receive tuple parameters and key word parameters, just like the function: def func(*args, **kwargs):pass How to use it =============== test_call.html {% expr "limodou" as name %} {% call "test/test_sub.html" with "a"|capfirst "b" title="title1" %}<br/> {% call "test/test_sub.html" with "c" "d" title="title2" %} expr is also a custom tag written by me. It'll calculate a python expression and save to result to a variable. In this case, the variable it "name". test_sub.html {% for i in args %}{{ i }}{% endfor %} <h2>{{ title }}</h2> <p>{{ name }}</p> <h3>args</h3> {{ args }} <h3>kwargs</h3> {{ kwargs }} And you also can see, call tag will auto create args and kwargs context variables. I hope this will be some useful.

  • tag
Read More

limodou has posted 18 snippets.