分类 "Python" 下的文章

问题:python中如果存在目录或文件就删除目录或文件

解决:使用os.path

方法:

import os
upload_dir = os.path.realpath(os.path.join(os.path.dirname(__file__),
                              "../static/uploads/attach"))
if not os.path.exists(upload_dir):
    os.makedirs(upload_dir)
if os.path.exists(upload_dir):
    os.rmdir(upload_dir)

fname = self.get_argument('fname','')
org_id = self.current_user.org_id
school_dir = os.path.realpath(os.path.join(os.path.dirname(__file__),
                              "../static/uploads/attach/%d"%org_id))
file_path = os.path.join(school_dir, fname)
if os.path.exists(file_path):
    os.remove(file_path)

问题:在python中想读取字典怎么办

解决:有多种方法

方法:

users = {"name":"haha", "age":23, "class":3, "school":"中华大学"}
注:将json格式的str转换成字典,其中必须为双引号

{% for k in users %}
{{ k }} {{ users[k] }}
{% end %}

{% for k in users.keys() %}
{{ k }} {{ users[k] }}
{% end %}

{% for k,v in users.items() %}
{{ k }} {{ v }}
{% end %}

{% for k,v in enumerate(users) %}
{{ k }} {{ v }} {{ users[v] }}
{% end %}
注:此时的k为从0开始的序号

问题:python中想将登录判断封装成一个方法,就不用每次都重写一遍了

解决:python提供装饰器功能,使用装饰器可以很简单的实现

方法:

def login_required(user_type="any"):
    """
        Decorate methods with this to require that the user be logged in.
    """ 
    def decorator(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            if not self.current_user:
                if self.request.method in ("GET", "HEAD"):
                    self.redirect("/login?r=%s" % urllib.quote(self.request.path))
                    return raise tornado.web.HTTPError(403)
                if user_type == "admin":
                    type_byte = 2
                else:
                    type_byte = 1
                if not self.current_user.type & type_byte:
                    self.write("无相应权限查看本页内容")
                    return
                return method(self, *args, **kwargs)
            return wrapper
        return decorator

阅读全文

问题:python如何对list进行排序

方法:

对一个list或者tunple根据参数来排序
L = [(1,1,2,3),(5,3,6,2),(2,2,1,2),(4,2,1,3),(1,2,1,2)]
L.sort(key=lambda x:(x[0],x[2]))

>>输出L:[(1, 2, 1, 2), (1, 1, 2, 3), (2, 2, 1, 2), (4, 2, 1, 3), (5, 3, 6, 2)]
L.sort(key=lambda x:(x[0],x[2]),reverse=True)逆序排列
[(5, 3, 6, 2), (4, 2, 1, 3), (2, 2, 1, 2), (1, 1, 2, 3), (1, 2, 1, 2)]
对于数据排序,可以直接加负号
L.sort(key=lambda x:(x[0],-x[2]))
[(1, 1, 2, 3), (1, 2, 1, 2), (2, 2, 1, 2), (4, 2, 1, 3), (5, 3, 6, 2)]