Karrigell for Python(老外的一篇介绍)

http://www.devshed.com/c/a/Python/Karrigell-for-Python/

Karrigell的基本用法,文章写的清晰简洁

Since Python is not specifically designed for web development, a number of technologies created by Python users exist that aim to provide a web development environment. While the exact approach to the situation varies among each framework, a few of these frameworks really stand out in the crowd. One such framework is Karrigell. Read on to learn more.

Introduction

While Karrigell is very powerful and flexible, offering multiple solutions to web development, it is surprisingly simple to set up and work with. Python novices won’t find any obstacles when working with Karrigell, and Python experts won’t feel too limited. It offers its own web server that gets the job done, but it also can be easily integrated with technologies such as Apache, so you do not have to sacrifice the use of other technologies when choosing Karrigell.

This article will guide you through the installation of Karrigell and will explore some of the capabilities of the web framework.

Installing Karrigell

Fortunately, there really isn’t any complicated magic involved with the installation of Karrigell. The obvious first step is to obtain the web framework, available at SourceForge:

http://sourceforge.net/projects/karrigell

Once you’ve downloaded Karrigell, extract it to an easily accessible directory, such as . Next, then simply execute Karrigell.py to start the built-in server. If you only want to run the included server and not set up Karrigell to work with another web server, your work is done, and you may safely skip to the next section.

Otherwise, you’ll need to configure your web server to interact with Karrigell. We’ll take a look at Apache. We’ll need the Karrigell web server to run behind Apache, so that Apache can pass off the relevant requests to Karrigell.

Since Apache will likely be running on port 80, you will need to set the Karrigell server on another port. You can either do this through the command line or by editing Karrigell’s configuration file. We’ll use port 8080 for Karrigell. The first method works something like this:

C:Karrigell>Karrigell.py -P 8080

To change Karrigell’s configuration file to set a default port, simply add this to Karrigell.ini:

port=8080

Now we have to configure Apache to redirect requests for Karrigell. Likely, you will want Apache to deal with all the static files of your website, along with other technologies such as PHP. To do this, you can create identical directory structures in both Karrigell and Apache – or at least for the directors where you want to utilize Karrigell – and configure Apache to redirect requests to Karrigell-associated files to the Karrigell server. All you need to do to set this up is add these lines to Apache’s httpd.conf file:

RewriteEngine On
RewriteRule ^/(.*).py(.*) http://localhost:8080/$1.py$2 [L,P]
RewriteRule ^/(.*).ks(.*) http://localhost:8080/$1.ks$2 [L,P]
RewriteRule ^/(.*).hip(.*) http://localhost:8080/$1.hip$2 [L,P]
RewriteRule ^/(.*).pih(.*) http://localhost:8080/$1.pih$2 [P]

If you want to, you can also set Apache to redirect all of the particular files in a directory to Karrigell. We’ll be using a directory called testarea throughout this article, so to configure Apache to redirect all requests to a file within that directory to Karrigell, add this to httpd.conf:

RewriteEngine On
RewriteRule ^/testarea(.*) http://localhost:8080/testarea$1 [P]

You could also modify the first set of configuration directives so that they only apply to a certain directory:

RewriteEngine On
RewriteRule ^/testarea/(.*).py(.*)
http://localhost:8080/testarea/$1.py$2 [L,P]
RewriteRule ^/testarea/(.*).ks(.*)
http://localhost:8080/testarea/$1.ks$2 [L,P]
RewriteRule ^/testarea/(.*).hip(.*)
http://localhost:8080/testarea/$1.hip$2 [L,P]
RewriteRule ^/testarea/(.*).pih(.*)
http://localhost:8080/testarea/$1.pih$2 [P]

{mospagebreak title=Scripts and Services}

The first two methods Karrigell presents to developers are scripts and services. A script is simply a Python script that uses print to output to the user’s browser. If you haven’t done so already, create a testarea directory, and we can begin our first script. Create the file test.py:

print “<center>”
print “Hello!”
print “<br /><br />”
print “Karrigell is configured and working.”
print “</center>”

Point your browser to the file, and if you have Karrigell set up as described above, you should see the message described above.

Form data is fairly easy to handle with Python scripts. Let’s create a simple script whose output differs depending on whether the user has specified his or her name in a form. Name it askName.py:

if QUERY.has_key ( “name” ):
   print “Your name is”, _name + “.”
else:
   print “What is your name?<br />”
   print “<form>”
   print “<input type=’text’ name=’name’ /><br />”
   print “<input type=’submit’ value=’Proceed’ />”
   print “</form>”

Services are written like Python scripts, too. However, they are designed to map requests to functions defined by the user. The desired function is passed along in the URL after the name of the service. For example, the following URL would call the test function of the service test.ks:

http://localhost/testarea/test.ks/test

Let’s actually create the test.ks service:

def index():
   print “Index function.”
def test():
   print “Test function.”

If you call the script without passing a function name, then you will be redirected to the index function. If you call the script passing the test function name, then the test function will be executed. Attempting to call a function not defined will produce an error.

Configuring services to accept form data is quite easy. Let’s recreate askName.py as the service askName.ks:

def index():
   print “What is your name?<br />”
   print “<form action=’nameSubmit’>”
   print “<input type=’text’ name=’name’ /><br />”
   print “<input type=’submit’ value=’Proceed’ />”
   print “</form>”
def nameSubmit ( name ):
   print “Your name is”, name + “.”

Of course, making every single one of your service’s functions accessible to the outside world could be a security hazard. To prevent users from accessing certain functions, simply prefix them with an underscore:

def _private():
   pass

Attempting to access the _private function will result in an error message.

{mospagebreak title=Being HIP}

In askName.py, one thing seems to be very noticeable: there are a lot of printstatements in the code. Wouldn’t it be nice if we could eliminate them? Fortunately, Karrigell provides a method that does just that. It’s called HTML Inside Python, and it allows all those nasty print statements to be eliminated. It isn’t very hard to convert askName.py to an HTML in Python file, either. We simply need to remove the print statements and change the extension. Delete askName.py’s print statements and rename it to askName.hip:

if QUERY.has_key ( “name” ):
   “Your name is”, _name + “.”
else:
   “What is your name?<br />”
   “<form method=’POST’>”
   “<input type=’text’ name=’name’ /><br />”
   “<input type=’submit’ value=’Proceed’ />”
   “</form>”

Truthfully, that’s all there is to HTML Inside Python. Karrigell will examine your file and add print statements when necessary. HTML Inside Python is a wonderful demonstration of the simplicity of Karrigell.

Python Inside HTML

Since Karrigell features HTML Inside Python, it’s only logical to contain Python Inside HTML. The underlying idea – and even the look of the finished code – is common, and it’s been featured in other frameworks. Special tags are wrapped around Python code, and the overall result is sent to the user’s browser. Let’s create a simple example, random.pih:

<% import random %>
Random number: <b><% print random.random() %></b>

As you can see, the concept behind Python Inside HTML is pretty simple. Also, note that the block of code that prints the random number could be shortened even more:

<%= random.random() %>

However, what about more complex operations, such as handling form data? Form data can be accessed just like it can be in Python scripts. Here is a recreation of the askName.py script, called askName.pih:

<% if QUERY.has_key ( “name” ): %>
   Your name is <%= _name %>.
<% end %>
<% else: %>
   What is your name?<br />
   <form method=’POST’>
   <input type=’text’ name=’name’ /><br />
   <input type=’submit’ value=’Proceed’ />
   </form>
<% end %>

Notice the use of <% end %>. This simply marks the end of a block of indentation, such as the indentation called for by our conditional statement. An alternative is the indent tag, which uses the indentation present in the code:

<indent>
<% if QUERY.has_key ( “name” ): %>
   Your name is <%= _name %>.
<% else: %>
   What is your name?<br />
   <form method=’POST’>
   <input type=’text’ name=’name’ /><br />
   <input type=’submit’ value=’Proceed’ />
   </form>
</indent>

{mospagebreak title=A Few More Features}

Although I’m not a huge fan of the practice, tags can be generated within Python scripts, as shown here in tagTest.py:

from HTMLTags import *

print CENTER ( B ( “Test.” ) )

Sessions are also possible with Karrigell, and Karrigell presents a nice, object-oriented approach to sessions. Let’s create a simple script that demonstrates sessions in Karrigell. Upon accessing the script for the first time, the user will receive a “lucky number” of sorts. If the user refreshes, the same number will still appear since it will be stored inside of a session. However, the user will be given the option of resetting his or her lucky number by closing the session. Create a Karrigell service named luckyNumber.ks in which to house this script:

import random

user = Session()

def index():
   if not “luckyNumber” in dir ( user ):
      user.luckyNumber = random.randint ( 0, 20 )
   print “Your lucky number:”, user.luckyNumber
   print “<br /><br />”
   print “<a href=’reset’>Reset Lucky Number</a>”
def reset():
   user.close()
   print “Your lucky number has been reset.”
   print “<br /><br />”
   print “<a href=’index’>Back</a>”

Conclusion

Karrigell offers four methods of web development using Python: Python scripts, Karrigell services, HTML Inside Python and Python Inside HTML. Each method is unique and has its benefits, but they all share one thing in common: each method is very simple to employ in applications. Karrigell approaches web development in a straightforward manner, presenting simple solutions to a simple problem. Even installing Karrigell and configuring Apache and Karrigell to interact is a surprisingly simple process. Because of all this, Karrigell appeals to both newcomers and experts in Python alike.

时间: 2024-10-29 19:10:36

Karrigell for Python(老外的一篇介绍)的相关文章

实战篇一 python常用模块和库介绍

# [email protected] coding: utf-8 [email protected] -- Python 常用模块和库介绍 第一部分:json模块介绍 import json 将一个Python数据结构转换为JSON: dict_ = {1:2, 3:4, "55":"66"} # test json.dumps print type(dict_), dict_ json_str = json.dumps(dict_) print "js

python 面向对象(进阶篇)

上一篇<Python 面向对象(初级篇)>文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使用(可以讲多函数中公用的变量封装到对象中) 对象,根据模板创建的实例(即:对象),实例用于调用被包装在类中的函数 面向对象三大特性:封装.继承和多态 本篇将详细介绍Python 类的成员.成员修饰符.类的特殊成员. 类的成员 类的成员可以分为三大类:字段.方法和属性 注:所有成员中,只有普通字段的内容保存对象

Python第一周基础篇

<感言:首先感谢alex老师精彩课程,第一周的第一天,随着金角大王的豪言壮语般的心灵鸡汤完美收场.此刻坐在电脑前的我仍是热血澎湃,下定决心好好跟着大王一起学好python> ----祝老师教师节快乐                                      Python第一周基础篇 博文结构: --1--python2.*与python3.*主要区别 --2--python安装与配置 --3--PyCharm开发工具的安装与配置 --4--变量的定义 --5--注释的使用 --

图解Python 【第五篇】:面向对象-类-初级基础篇

由于类的内容比较多,分为类-初级基础篇和类-进阶篇 类的内容总览图: 本节内容一览图: 今天只讲类的基础的面向对象的特性 前言总结介绍: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个"函数"供使用(可以讲多函数中公用的变量封装到对象中) 对象,根据模板创建的实例(即:对象),实例用于调用被包装在类中的函数,对象是一个类的实例 实例(instance):一个对象的实例化实现. 标识(identity):每个对象的实例都需要一个可

运维学python之爬虫高级篇(六)scrapy模拟登陆

上一篇介绍了如何爬取豆瓣TOP250的相关内容,今天我们来模拟登陆GitHub. 1 环境配置 语言:Python 3.6.1 IDE: Pycharm 浏览器:firefox 抓包工具:fiddler 爬虫框架:Scrapy 1.5.0 操作系统:Windows 10 家庭中文版 2 爬取前分析 分析登陆提交信息分析登陆信息我使用的是fiddler,fiddler的使用方法就不作介绍了,大家可以自行搜索,首先我们打开github的登陆页面,输入用户名密码,提交查看fiddler获取的信息,我这

python从零开始 -- 第0篇

为什么选择python以及版本选择 学习资料 1. 为什么选择python以及版本选择: Python  好玩,强大,更多关于关于为什么选择Python,在  编程小白的第一本 Python 入门书  有详细介绍在此不重复粘贴了,当然建议直接看完此书,干货十足. 关于版本: 1989年,Guido van Rossum大神圣诞节无聊,决定开发为当时正在构思的一个新的脚本语言写一个解释器,因此在次年诞生了Python(膜拜) 2000年10月,Python 2.0正式发布 2010年,Python

python从零开始 -- 第2篇之python版本差异

python从零开始 -- 第2篇之python版本差异 第0篇开始,咱们就说选择 python 3.x,一般来说,咱们面临选择的时候总是想了解更多一点,并且版本之间的对比能引申出很多有意思的故事和知识点,对于加深认识也是很有帮助. 让我们先从python发展史开始吧 这份官方文档着python详细的版本列表,这是中文版介绍,一长串的内容都是python生命力的体现,python在TIOBE排行榜上也是排名靠前,现已超越 c++ 成为探花,仅次于 Java 和 C,看到这里是不是感叹python

由浅入深,走进Python装饰器-----第二篇:进阶--函数装饰函数

上一篇:由浅入深,走进Python装饰器-----第一篇:基础 装饰器的使用种类: # 第一种 @函数 被装饰函数 # 第二种 @函数 被装饰类 # 第三种 @类 被装饰类 # 第四种 @函数 被装饰函数 本篇介绍第一种 @函数 被装饰函数 1.1 对带参数的原函数进行修饰 # 默认将old函数的参数传给outer里面的第一层函数 def outer(f): def inner(var): print("1 我是outer函数,接收外部传进来的old :",f) print("

Python常用的库简单介绍一下

Python常用的库简单介绍一下fuzzywuzzy ,字符串模糊匹配. esmre ,正则表达式的加速器. colorama 主要用来给文本添加各种颜色,并且非常简单易用. Prettytable 主要用于在终端或浏览器端构建格式化的输出. difflib ,[Python]标准库,计算文本差异 . Levenshtein ,快速计算字符串相似度. Chardet 字符编码探测器,可以自动检测文本.网页.xml的编码. shortuuid ,一组简洁URL/UUID函数库. ftfy ,Uni