Скачать презентацию Python and Web Development n n n Can t Скачать презентацию Python and Web Development n n n Can t

50bc4f48d2c625b9fa61020d95df01df.ppt

  • Количество слайдов: 42

Python and Web Development n n n Can’t possibly do justice in 60 minutes Python and Web Development n n n Can’t possibly do justice in 60 minutes So we’ll be flying at 30, 000 feet. Quick URLs: http: //python. org/ http: //webware. sourceforge. net/ http: //www. python. org/cgibin/moin/Web. Programming

Who is your presenter? n n n n n Chuck Esterbrook Independent Contractor/Consultant since Who is your presenter? n n n n n Chuck Esterbrook Independent Contractor/Consultant since Spring 2000 Most work since then has been in Python But also Java, C# and even (gasp!) VB Going backwards: Project Manager, Senior Software Engineer, B. S. in Comp Sci Have used a variety of tools for a variety of companies in a variety of roles My programming language of choice is Python Author of O. S. product: Webware for Python Co-founder of SANDPYT

Why Python? n n n At a really high level: Productivity In IT, Productivity Why Python? n n n At a really high level: Productivity In IT, Productivity = Happiness Python was designed to be n n n “-able” as in readable, writeable and maintainable Easy to use Powerful Balances all of these Contrasted with lack of balance in other langs: n n n Perl: writeability to the detriment of others C++: performance to the detriment of others VB: legacy BASIC to the detriment of everything

Python productivity: Ubiquity n n n Can’t stress this enough: Python works well in Python productivity: Ubiquity n n n Can’t stress this enough: Python works well in almost all areas: web, gui, sys admin, simulation, finances, etc. So you can take your acquired skills and libraries everywhere Hit the ground running Easily reuse your own home-brewed libs, 3 rd party libs, etc. Contrast: n n n C++: Not ideal for sys admin or rapid development Perl: Not ideal for large scale or team-based VB: Not ideal for anything

Python: Selective popularity n n Python has no marketing budget, but Still gets vote Python: Selective popularity n n Python has no marketing budget, but Still gets vote of confidence by successful, wellknown companies: n n n Google Yahoo! Industrial Light & Magic These companies can afford and use any tools they want. Their choices include Python. Dr. Dobb’s Journal lists Python across the top of their mag. cover right beside Linux, XML, Win 32, etc.

Python programs are problem-oriented n n n Common sensation among new Python programmers, including Python programs are problem-oriented n n n Common sensation among new Python programmers, including myself: “In Python, I’m dealing with my problem instead of my language. ” Again, contrast: n n n C++: obscure compilation problems Perl: reading obscure code VB(6): no inheritance, no exception handling, etc.

What does Python look like? n Let’s get this out of the way: # What does Python look like? n Let’s get this out of the way: # Hello. World. py print “Hello, world”

" src="http://present5.com/presentation/50bc4f48d2c625b9fa61020d95df01df/image-8.jpg" alt="#!/usr/bin/env python # What does Python really look like? # like "wc -l " /> #!/usr/bin/env python # What does Python really look like? # like "wc -l | sort -n" import sys def main(args=None): if args is None: args = sys. argv lines. Per. File = [] for filename in args[1: ]: # arg[0] is prog n = len(open(filename). readlines()) t = (n, filename) lines. Per. File. append(t) lines. Per. File. sort(my. Compare) # print it for lines, filename in lines. Per. File: print "%4 i %s" % (lines, filename) def my. Compare(t 1, t 2): return cmp(t 1[0], t 2[0]) if __name__=='__main__': main()

What my Python really looks like. n n Almost all my Python is Object-Oriented. What my Python really looks like. n n Almost all my Python is Object-Oriented. We’re talking classes, objects and methods. Python is easiest OO language I’ve used to date. Like rest of language: n n Simple; easy to learn Powerful Gets to the point More OO specifics: n n Full dynamic binding Easy introspection (aka “reflection”) Easy hooks for operator overloading Multiple inheritance (see next slide)

What once was evil is now good! n n n I left C++ thinking What once was evil is now good! n n n I left C++ thinking “multiple inheritance is bad” and “operator overloading is bad” After experiencing them in Python, I realize both are good if done right Multiple inheritance n n n Full dynamic binding No strange compilation errors, or mysterious crashes Used mostly as a “mix-in” style http: //www. linuxjournal. com/article. php? sid=4540 Imagine if Java interfaces provided “default” or “canonical” implementations of some methods. Bottom line: m. i. increases productivity Operator overloading n Just normal operators

# What does Python OOP look like? class Node: def __init__(self, name, super. Node=None): # What does Python OOP look like? class Node: def __init__(self, name, super. Node=None): self. name = name self. super. Node = super. Node if super. Node: super. Node. sub. Nodes. append(self) self. sub. Nodes = [] def dump(self, out=None): if out is None: out = sys. stdout self. _dump(out, 0) def _dump(self, out, indent): out. write(' '*4*indent + str(self) + 'n') indent += 1 for node in self. sub. Nodes: node. _dump(out, indent) def __repr__(self): return '<%s %r %i-subnodes 0 x%x>' % ( self. __class__. __name__, self. name, len(self. sub. Nodes), id(self))

Output animal = Node('animal') mammal = Node('mammal', animal) cat = Node('cat', mammal) dog = Output animal = Node('animal') mammal = Node('mammal', animal) cat = Node('cat', mammal) dog = Node('dog', mammal) insect = Node('insect', animal) animal. dump()

Other Python Highlights n n Built in lists and dictionaries Exception handling n n Other Python Highlights n n Built in lists and dictionaries Exception handling n n Full garbage collection Imperative with common constructs n n n Try…except…else…finally raise Some. Error(args) for, while, break, continue, func() Var args by position or keyword Doc strings Modules and packages Platform independent by default and specific by choice

Learning Python n n Lots of options! I like: http: //python. org/doc/current/tut. html All Learning Python n n Lots of options! I like: http: //python. org/doc/current/tut. html All the links you need: http: //python. org/topics/learn/ Books abound (check Book. Pool. com, Amazon) SANDPYT – San Diego Python User’s Group http: //sandpyt. org/

Web dev n n One hour presentation as intro to both Python and Python Web dev n n One hour presentation as intro to both Python and Python web dev! (heh) Web dev options: n n n CGI: Bleck. n Might be fast enough for some sites, but certainly feels wasteful. n Encourages nekkid scripts. i. e. , non-OO Fast. CGI: A band-aid useful for existing CGI apps. App Servers n Webware n Zope n Others

What is Webware for Python? n n n n Server-side web development tools that What is Webware for Python? n n n n Server-side web development tools that leverage Python. Most similar to Java web tools and Apple Web. Objects Some overlap with CGI, CF, Zope, PHP, ASP… Covers common needs of web developers Open source development and community Python license Cross-platform; works equally well on: n n Posix in its many flavors (Linux, BSD, Solaris, UNIX…) Windows NT/2000/XP Modular architecture: components can easily be used together or independently Object-oriented

Comparisons to other Tools n n n n No religious fervor allowed during this Comparisons to other Tools n n n n No religious fervor allowed during this slide. I designed Webware after using various web tools. So I addressed shortcomings from the start. Unlike PHP, Webware leverages a general purpose language (Python) and everything that comes with it Same with Cold. Fusion; also not closed-source Unlike CGI, Webware is fast and provides a good OO structure Similar to Java web tools, but better language and less bureaucratic APIs Zope: WW is less monolithic, direct access to Python, programmer-oriented, etc.

What is in Webware? n n The heart of Webware is Web. Kit, the What is in Webware? n n The heart of Webware is Web. Kit, the application server And: n n n Python Server Pages (PSP) Task. Kit Middle. Kit User. Kit All of these are Python packages Web. Kit includes the App Server which you will run continuously as with other servers (web, db, etc. )

Web. Kit n n A fast, easy-to-use Python application server Multi-threading, not forking n Web. Kit n n A fast, easy-to-use Python application server Multi-threading, not forking n n n Supports multiple styles of development: n n Makes persistent data easier Works well on Windows Servlets Python Server Pages (PSP) Custom file extension handling Extensible n n n Servlet factories Plug-ins Import any Python module. ; -)

Is it real? Yes! n n n n n Been around since spring 2000 Is it real? Yes! n n n n n Been around since spring 2000 including contractual work Stable and mature Used in several real-world, commercial projects: http: //webware. sf. net/wiki//Who. Is. Using. Webware http: //Stock. Alerts. com/ http: //Steves. Stock. Picks. com/ http: //www. Vorbis. com/ - open free audio http: //www. Electronic. Appraiser. com/ - real estate http: //Patient. Wire. com - e-commerce for optometry And others including many private Intranets

Architecture Browser Server XML-RPC client 80 80 Apache Web. Kit. cgi 8086 mod_webkit 8086 Architecture Browser Server XML-RPC client 80 80 Apache Web. Kit. cgi 8086 mod_webkit 8086 Web. Kit Servlets Filesystem PSPs Database

Starting the app server n n Installation instructions are included with Webware Ways to Starting the app server n n Installation instructions are included with Webware Ways to connect web server & app server: n n n Web. Kit. cgi – least common denominator mod_webkit – fast In your working directory, run: n n Unix: n cd /usr/local/webapps/webinator n. /App. Server Windows: n cd C: My. Web. AppsWebinator n App. Server

Using the Example servlets and PSP’s n To use the CGI adapter, surf to: Using the Example servlets and PSP’s n To use the CGI adapter, surf to: n n To use the mod_webkit adapter, surf to: n n http: //localhost/cgi-bin/Web. Kit. cgi http: //localhost/webkit Experiment and enjoy!

Servlets n n A Python class located in a module of the same name Servlets n n A Python class located in a module of the same name Must inherit from Web. Kit. Servlet or one of its subclasses: n n n A common technique is to make your own subclass of Web. Kit. Page called Site. Page which will contain: n n n Web. Kit. HTTPServlet Web. Kit. Page Utility methods Overrides of default behavior in Web. Kit. Page Simplest servlet: from Web. Kit. Page import Page class Hello. World(Page): def write. Content(self): self. writeln(‘Hello, World!’)

The Request-Response Cycle n User initiates a request: n n This activates the My. The Request-Response Cycle n User initiates a request: n n This activates the My. Context context, and the My. Servlet servlet, based on settings in Application. config n n n http: //localhost/webkit/My. Context/My. Servlet Note: no extension was specified, even though the file is called My. Servlet. py There are settings in Application. config that control the way extensions are processed An instance of the My. Servlet class is pulled out of a pool of My. Servlet instances, OR if the pool is empty then a new My. Servlet instance is created. A Transaction object is created. These methods are called on the My. Servlet instance: n n Servlet. awake(transaction) Servlet. respond(transaction) Servlet. sleep(transaction) The My. Servlet instance is returned to its pool of instances.

HTTPRequest n n Derived from generic Request base class Contains data sent by the HTTPRequest n n Derived from generic Request base class Contains data sent by the browser: n n n n GET and POST variables: n. field(name, [default]) n. has. Field(name) n. fields() Cookies: n. cookie(name, [default]) n. has. Cookie(name) n. cookies() If you don’t care whether it’s a field or cookie: n. value(name, [default]) n. has. Value(name) n. values() CGI environment variables Various forms of the URL Server-side paths etc.

HTTPResponse n n Derived from generic Response base class Contains data returned to the HTTPResponse n n Derived from generic Response base class Contains data returned to the browser n n . write(text) – send text response to the browser n Normally all text is accumulated in a buffer, then sent all at once at the end of servlet processing. set. Header(name, value) – set an HTTP header. flush() – flush all headers and accumulated text; used for: n Streaming large files n Displaying partial results for slow servlets. send. Redirect(url) – sets HTTP headers for a redirect

Page: Convenience Methods n Access to the transaction and its objects: n n Writing Page: Convenience Methods n Access to the transaction and its objects: n n Writing response data: n n . html. Encode(). url. Encode() Passing control to another servlet: n n . write() – equivalent to. response(). writeln() – adds a newline at the end Utility methods: n n . transaction(), . response(), . request(), . session(), . application() . forward(). include. URL(). call. Method. Of. Servlet() Whatever else YOU decide to add to your Site. Page

Page: Methods Called During A Request n n n . respond() usually calls. write. Page: Methods Called During A Request n n n . respond() usually calls. write. HTML() Override. write. HTML() in your servlet if you want your servlet to provide the full output But, by default. write. HTML() invokes a convenient sequence of method calls: n n n . write. Doc. Type() – override this if you don’t want to use HTML 4. 01 Transitional. writeln(‘’). write. Head(). write. Body(). writeln(‘’)

Forwarding & Including n self. forward(‘Another. Servlet’) n n n Analogous to a redirect Forwarding & Including n self. forward(‘Another. Servlet’) n n n Analogous to a redirect that happens entirely within Web. Kit Bundles up the current Request into a new Transaction Passes that transaction through the normal Request. Response cycle with the indicated servlet When that servlet is done, control returns to the calling servlet, but all response text and headers from the calling servlet are discarded Useful for implementing a “controller” servlet that examines the request and passes it on to another servlet for processing self. include. URL(‘Another. Servlet’) n Similar to. forward(), except that the output from the called servlet is included in the response, instead of replacing the response.

Sessions n n Store user-specific data that must persist from one request to the Sessions n n Store user-specific data that must persist from one request to the next Sessions expire after some number of minutes of inactivity n n The usual interface: n n n Controlled using Session. Timeout config variable. value(name, [default]). has. Value(name). values(). set. Value(name, value) And dictionary-like access for values: n n sess = self. session() sess[‘user. Id’] = user. Id

PSP: Python Server Pages n n Mingle Python and HTML in the style of PSP: Python Server Pages n n Mingle Python and HTML in the style of JSP or ASP Include code using <% … %> Include evaluated expressions using <%= … %> Begin a block by ending code with a colon: <%for I in range(10): %> n End a block using the special tag: <%end%> n When the user requests a PSP: n n It is automatically compiled into a servlet class derived from Web. Kit. Page The body of your PSP is translated into a write. HTML() method

PSP Example <% def isprime(number): if number == 2: return 1 if number <= PSP Example <% def isprime(number): if number == 2: return 1 if number <= 1: return 0 for i in range(2, number/2): for j in range(2, i+1): if i*j == number: return 0 return 1 %>

Here are some numbers, and whether or not they are prime:

<%for i in range(1, 101): %> <%if isprime(i): %> <%=i%> is prime! <%end%><%else: %> <%=i%> is not prime. <%end%>

Web Services: XML-RPC n n Turn your Webware site into a “web service” Write Web Services: XML-RPC n n Turn your Webware site into a “web service” Write a servlet derived from XMLRPCServlet n n Define exposed. Methods() method that lists the methods you want to expose through XML-RPC Write your methods Sorry, no time for an example. Bottom line: n n Creating XML-RPC services in Webware is easy Using XML-RPC services in Python is easy

Error Reports (i. e. , Tracebacks) n If an unhandled exception occurs in a Error Reports (i. e. , Tracebacks) n If an unhandled exception occurs in a servlet: n n Application. config settings: n If Show. Debug. Info. On. Errors = 1, an HTML version of the traceback will be shown to the user; otherwise, a short generic error message is shown. n You can configure Web. Kit so that it sends the traceback by email: Email. Errors, Error. Email. Server, Error. Email. Headers n Include “fancy” traceback using Include. Fancy. Traceback and Fancy. Traceback. Context Your users will NOT report tracebacks, so set up emailing of fancy tracebacks!

Middle. Kit n n Object-Relational mapper Supports My. SQL and MS SQL Server. n Middle. Kit n n Object-Relational mapper Supports My. SQL and MS SQL Server. n n n Can be used anywhere, not just Web. Kit applications. Write an object model in a Comma-Separated Values (CSV) file using a spreadsheet n n n Postgre. SQL support soon? @@ check this Inheritance is supported Numbers, strings, enums, dates/times, object references, lists of objects (actually sets of objects) Compile the object model n n n This generates Python classes for each of your objects that contain accessor methods for all fields Also, an empty derived class is provided where you can add your own methods And, a SQL script is generated that you can run to create the tables

Cheetah n n n http: //www. cheetahtemplate. org/ A Python-powered template engine and code Cheetah n n n http: //www. cheetahtemplate. org/ A Python-powered template engine and code generator Uses the “dollar sign-pound sign” $# syntax found in Velocity, Web. Macro, et al. @@ Integrates tightly with Webware Can also be used as a standalone utility or combined with other tools Compared with PSP: n n Much more designer-friendly Perhaps less programmer-friendly?

Zope n n n I used Zope before Webware even existed. Then I wrote Zope n n n I used Zope before Webware even existed. Then I wrote Webware. Zope has strong “through the web” CMS and some nice built-in features if they matched your application. I found it monolithic and “interfering”. It squirreled Python away and wrapped it with DTML and UI. But Python was designed to be user-friendly from the start, so I wanted to use it in a natural environment.

Webware-Zope Quotes n “In Zope, I find myself writing a lot of External Methods Webware-Zope Quotes n “In Zope, I find myself writing a lot of External Methods to do the 'heavy lifting', and call them from within the DTML. In Web. Kit, the 'heavy lifting' is just part of the Python, not a requisite separate entity. n n Gary Perez - Jun 11, 2003 “I guess, it's the thinness of Webware. WW is ‘pro. Python’, which means, that everything you do is more than less directly done in Python. No DHTML, . . . This -at least IMO- is one of the strong points in Webware: it doesn't put anything between the application developer and Python. ” n Frank Barknecht - Jun 11, 2003

Choosing Webware or Zope n n If you’re more of a non-technical user, Zope’s Choosing Webware or Zope n n If you’re more of a non-technical user, Zope’s point-and-click WUI interface and templating, might appeal to you more. If you like programming in Python, Webware is more likely to appeal to you.

Other App Servers n n n Zope was only mature app server when I Other App Servers n n n Zope was only mature app server when I built Webware. I haven’t tracked the others at all. Most popular ones seem to be Skunk. Web, Quixote and possibly Twisted Matrix. Zope 3 is in development as successor to Zope 2. Webware is still going strong with new developers, new users and thousands of downloads.

That’s All! n n n Any questions? URLs: http: //python. org/ http: //webware. sourceforge. That’s All! n n n Any questions? URLs: http: //python. org/ http: //webware. sourceforge. net/ http: //www. python. org/cgibin/moin/Web. Programming