Thursday, March 12, 2009

How to combine ReST and Pygments

Many Python people use ReST for documentation their sourcecode, programs, scripts et cetera.But as the description at Using Pygments in ReST documents you need copy external/rst-directive.py to your code. It's not enough detail.

let me give you an example:
  1. Get it from the Cheese Shop.
  2. unzip the file and then open the external/rst-directive.py with your favorite text editor.
  3. edit the file under the //Lib/site-packages/docutils/parsers/rst/__init__.py
  4. add following code to the bottom of the file and save it.
  5. now you can generate the rest documnet with source code highlight.
Here is an example that I used:



# Set to True if you want inline CSS styles instead of classes
INLINESTYLES = True

from pygments.formatters import HtmlFormatter

# The default formatter
DEFAULT = HtmlFormatter(noclasses=INLINESTYLES)

# Add name -> formatter pairs for every variant you want to use
VARIANTS = {
'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True),

}


from docutils import nodes
from docutils.parsers.rst import directives

from pygments import highlight
from pygments.lexers import get_lexer_by_name, TextLexer

def pygments_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
try:
lexer = get_lexer_by_name(arguments[0])
except ValueError:
# no lexer found - use the text one instead of an exception
lexer = TextLexer()
# take an arbitrary option if more than one is given
formatter = options and VARIANTS[options.keys()[0]] or DEFAULT
parsed = highlight(u'\n'.join(content), lexer, formatter)
return [nodes.raw('', parsed, format='html')]

pygments_directive.arguments = (1, 0, 1)
pygments_directive.content = 1
pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS])

directives.register_directive('sourcecode', pygments_directive)

Monday, February 16, 2009

Introducing Bespin

Bespin proposes an open extensible web-based framework for code editing that aims to increase developer productivity, enable compelling user experiences, and promote the use of open standards.
Do you want a text editor? with syntax highlight,show line number,auto folder etc
It's really a cool stuff,try it!!!

Introducing Bespin from Dion Almaer on Vimeo.

Friday, December 26, 2008

Should I make a new wheel?

I must admit that I'm a pythonic,I like everything of python.After a long time to experiment Django. I think I need my own web framework.To tell you the turth,I'm a java fan previously.I like Hibernate,spring,struts etc.So I decided to make a simple but better web framework, its ORM like hibernate, its web architecture like spring, and may be I'll create a simple server, I refer to the Django,CherryPy ,both of them are enough good.may be I just need reuse them. who knows,but for now my plan is write a simple web server firstly. I think cherryPy's server is a good reference.

Tuesday, December 16, 2008

clean_data and cleaned_data

When we use the form object in Django,Frequently,we need validate the fields of the form.for example:
>>>python manage.py shell
>>>from pageage1 import MyForm
>>>form=MyForm({'username':'Eric','email':'test@test.com'})
>>>form.is_valid()
True

We could access the form's data by attribute form.data, If it's validated we can also access the valid data by attribute form.clean_data,but when you upgrade to Django 1.0,this attribute will be no long in use.Instead of it,you should use the attribute cleaned_data:
...
>>>form.clean_data # Django 0.96
>>>form.cleaned_data # Django 1.0

Monday, December 15, 2008

errors and has_errors

There is a slight difference between Django 1.0 and 0.95.When we use user authentication in Django,and we create pass a form object to login.html template for example.
<div style="margin-left: 40px;"> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Django Bookmarks - User Login</title>
</head>
<body>
<h1>User Login</h1>
{%if form.has_errors%}
<p>Your username and password didn't match.
Please try again.</p>
{%endif%}
<form method="post" action=".">
<p><label for="id_username">Username:</label>
{{ form.username }}</p>
<p><label for="id_password">Password:</label>
{{ form.password }}</p>
<input type="hidden" name="next" value="/">
<input type="submit" value="login">
</form>
</body>
</html>

In version 0.95,it's work fine.but if you run it under the version 1.0,you can't see the error message when you login-failing.The question is in Django 1.0,the attribute of form object is errors instead of has_error.so change the attribute it'll work well.

Thursday, November 27, 2008

How to write something in PDF by python

Did you ever meet this problem?your customer want to show their report by PDF format.I think so.I think the best lib to use is ReportLab ,you can download it from site and install it.Today I want to provide an simple example to illustrate how to use it,especially when you write something none standard character in it.Let's begin with a real example in our app,suppose you want to convert a text to a PDF.now you have a file at c:/log.txt,and you want to covert it to c:/h.pdf file.The code is :

#first we import necessary module.
from reportlab.pdfgen import canvas
#now,open the file which we want to covert to
f=open("c:/log.txt","rb")
#read each line in the file.
lines=f.readlines()
#create a canvas objects,it can write the string
#in the pdf
c=canvas.Canvas("c:/h.pdf")

#maybe the file we read was very big so we must
#consider that display them in multiple page
j=700 #for example it's height is 700 point
for row in lines:
#firstly, we do an encoding cover.
uniline=unicode(row,'latin-1')

if j==0:
j=700
#showPage method means,we want to write in next page
c.showPage()
else:
j=j-10
#drawString method will draw the text information in PDF
c.drawString(100, j, uniline.strip())
#don't forget close the file
f.close()
#don't forget save the canvas,otherwise,you can't see anything
#in the .pdf file
c.save()

It's simple that is,right?

Wednesday, November 26, 2008

The order of the Python's class inheritance

Every OOP language provide the inheritance feature.In Python one subclass could have multiple super class,For example:we have two class A and B,now we create another class C,it's inherit from A and B:
class A:
def method1(self):
print "this is the method1 of class A"
class B:
def method1(self):
print "this is the method2 of class B"
class C(A,B): #class C inherit from A and B
pass


c=C()
c.method1()#Now the question is which method will be call,A or B
#The result is:
this is the method1 of class A

That means,the inheritance rest with which super class in the starting location,in this example,class A in the zero position,so the method1 in class A will be call instead of class B