Code war of Angel


  • Home

  • Archives

Python标准库

Posted on 2018-11-09 | In Python

参考

  1. 正则 :re
  2. 测试
  • doctest
  • unittest
  1. 日志:logging
  2. 打印错误信息:sys.exc_info()

搭建Discuz论坛

Posted on 2018-11-08
  1. 下载包文件:Discuz论坛
    选择UTF版本
  2. 解压文件,实际代码目录为 /upload
  3. 配置Nginx

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    server {
    charset utf-8;
    client_max_body_size 128M;
    listen 80;
    server_name bbs.local.com;
    root /vagrant/bbs/upload/;
    index index.php;

    location ~ \.php$ {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass 127.0.0.1:9000; # 查看php-fpm.conf 文件 [www] listen 属性
    #fastcgi_pass unix:/var/run/php5-fpm.sock;
    try_files $uri =404;
    }
    }
  4. 如nginx报错

    1
    2
    3
    #nging/error.log
    2018/11/08 12:13:29 [error] 14591#14591: *339 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: , server: wiki.ainnovation.com, request: "GET /shaAdmin/index.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.2-fpm.sock:", host: ""
    检查fastcgi_pass属性配置
  5. 如Nginx 报404

    1
    2018/11/08 08:41:49 [error] 13474#13474: *1 "/home/abc/bbs/index.php" is not found (2: No such file or directory), client: 106.120.83.206, server:, request: "GET / HTTP/1.1", host: ""

需要检查文件权限及nginx进程用户是否有权限访问该目录

  • ps -aux|grep Nginx 查看work 进程所属用户
    nginx
  • 查看代码文件所属目录是否同一个用户/有访问权限
    如果你使用vagrant 环境,vagrant 共享目录默认用户是vagrant 可以通过vagrant配置文件修改

    1
    config.vm.synced_folder "./", "/vagrant",create:true, :owner=>"www", :group=>"www",:mount_options=>["dmode=775","fmode=775"]
  • 修改nginx 进程使用用户

    1
    2
    >>> vim /usr/local/nginx/conf/nginx.conf
    user www;
  1. 如你数据库使用阿里云/腾讯云,可能会出现报错
    页面报错信息: discuz Table ‘xxxxx.forum_post’ doesn’t exist
    数据库报错信息: 报错:#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
    可按以下sql手动创建表

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    CREATE TABLE IF NOT EXISTS `pre_forum_post` (
      `pid` int(10) unsigned NOT NULL,
      `fid` mediumint(8) unsigned NOT NULL DEFAULT '0',
      `tid` mediumint(8) unsigned NOT NULL DEFAULT '0',
      `first` tinyint(1) NOT NULL DEFAULT '0',
      `author` varchar(15) NOT NULL DEFAULT '',
      `authorid` mediumint(8) unsigned NOT NULL DEFAULT '0',
      `subject` varchar(80) NOT NULL DEFAULT '',
      `dateline` int(10) unsigned NOT NULL DEFAULT '0',
      `message` mediumtext NOT NULL,
      `useip` varchar(15) NOT NULL DEFAULT '',
      `port` smallint(6) unsigned NOT NULL DEFAULT '0',
      `invisible` tinyint(1) NOT NULL DEFAULT '0',
      `anonymous` tinyint(1) NOT NULL DEFAULT '0',
      `usesig` tinyint(1) NOT NULL DEFAULT '0',
      `htmlon` tinyint(1) NOT NULL DEFAULT '0',
      `bbcodeoff` tinyint(1) NOT NULL DEFAULT '0',
      `smileyoff` tinyint(1) NOT NULL DEFAULT '0',
      `parseurloff` tinyint(1) NOT NULL DEFAULT '0',
      `attachment` tinyint(1) NOT NULL DEFAULT '0',
      `rate` smallint(6) NOT NULL DEFAULT '0',
      `ratetimes` tinyint(3) unsigned NOT NULL DEFAULT '0',
      `status` int(10) NOT NULL DEFAULT '0',
      `tags` varchar(255) NOT NULL DEFAULT '0',
      `comment` tinyint(1) NOT NULL DEFAULT '0',
      `replycredit` int(10) NOT NULL DEFAULT '0',
      `position` int(8) unsigned NOT NULL AUTO_INCREMENT,
      PRIMARY KEY (`position`,`tid`),
      UNIQUE KEY `pid` (`pid`),
      KEY `fid` (`fid`),
      KEY `authorid` (`authorid`,`invisible`),
      KEY `dateline` (`dateline`),
      KEY `invisible` (`invisible`),
      KEY `displayorder` (`tid`,`invisible`,`dateline`),
      KEY `first` (`tid`,`first`)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
  2. 修改论坛首页头部
    文件位于:/template/default/commom/header.htm

  3. 修改论坛logo
    文件位于:/static/image/common/logo.png
  4. 技巧:
  • 用户组编辑器控制/访问:界面-用户组-编辑-(论坛相关-帖子设置)

Python的类

Posted on 2018-11-07 | In Python
  1. 作用域:一个定义于某模块中的函数的全局作用域是该模块的命名空间,而不是该函数的别名被定义或调用的位置
  2. example

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    class MyClass:
    i = 12345
    # 类的实例化操作会自动为新创建的类实例调用 __init__() 方法
    def __init__(self,realpart, imagpart):
    self.data = []
    self.r = real part
    self.im = imagpart
    # 一般方法的第一个参数被命名为 self,这仅仅是一个约定
    def f(self):
    return 'hello world'

    >>> x = MyClass('realpart','imagpart')
  3. 继承

    1
    2
    3
    4
    5
    6
    7
    8
    class DerivedClassName(BaseClassName):
    pass
    class DerivedClassName(modname.BaseClassName):
    pass

    # 多继承
    class DerivedClassName(Base1, Base2, Base3):
    pass
  • 派生类可能会覆盖其基类的方法。因为方法调用同一个对象中的其它方法时没有特权,基类的方法调用同一个基类的方法时,可能实际上最终调用了派生类中的覆盖方法。
  • 检查继承类型:
    1
    2
    3
    4
    # 函数 isinstance()用于检查实例类型
    isinstance(obj, int)
    # 函数 issubclass()用于检查类继承
    issubclass(bool, int)
  1. public: name
    protect : _name
    private: __name

  2. 迭代器:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class Reverse:
    # 定义一个 __iter__()方法,使其返回一个带有 __next__()方法的对象。
    """Iterator for looping over a sequence backwards."""
    def __init__(self, data):
    self.data = data
    self.index = len(data)
    def __iter__(self):
    return self
    def __next__(self):
    if self.index == 0:
    raise StopIteration
    self.index = self.index - 1
    return self.data[self.index]
  3. 生成器

    1
    2
    3
    4
    5
    6
    def reverse(data):
    for index in range(len(data)-1, -1, -1):
    yield data[index]
    for char in reverse('golf'):
    print(char)
    `

Python的模块与包

Posted on 2018-11-07 | In Python

Python模块

  1. 引入模块

    1
    2
    3
    4
    5
    6
    7
    # 方式一
    import module
    module.function('xxx')
    # 方式二
    from module import * #导入所有除了以下划线( _ )开头的命名
    # from module import function,function1,function2
    function('xxx')
  2. 以脚本方式运行模块,name 被设置为 “main“

    1
    2
    3
    >>> python module.py
    if __name__ == "__main__":
    pass
  3. 模块搜索路径

  • 当前目录
  • sys.path 变量中给出的目录列表
    • 输入脚本的目录(当前目录)
    • 环境变量 PYTHONPATH表示的目录列表中搜索
    • Python 默认安装路径中搜索
  1. 模块编译:
  • 为加快加载模块的速度,Python 会在 __pycache__ 目录下以 module.version.pyc 名字缓存每个模块编译后的版本
  • Python 会检查源文件与编译版的修改日期以确定它是否过期并需要重新编译
  • Python会永远重新编译而且不会存储直接从命令行加载的模块
  • 如果没有源模块它不会检查缓存
  1. 标准模块库,是一个依赖于底层平台的配置选项集合
  2. 包
    包结构
  • 必须包含___init___.py
  • ___all___ = [“echo”, “surround”, “reverse”] 指定*导入的子模块集合
  • 如果没有定义 ___all_ , from sound.effects import * 语句不会__从 sound.effects 包中导入所有的子模块
  • 导入方式
    `
    import sound.effects.echo
    sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

from sound.effects import echo
echo.echofilter(input, output, delay=0.7, atten=4)

Python协程优化

Posted on 2018-11-06 | In Python
  1. 协程增加超时处理 :https://www.jianshu.com/p/0efdc952e8ca
    • 报错信息
      1
      aiohttp.client_exceptions.ServerDisconnectedError
  • 处理
    1
    2
    3
    4
    5
    6
    7
    8
    import async_timeout
    # The event loop will ensure to cancel the waiting task when that timeout is reached and the task hasn't completed yet.
    with async_timeout.timeout(0.001):
    # 捕捉timeout错误
    try:
    async with session.get('https://github.com') as r:
    exception Exception as e:
    print(repr(e))
  1. 实测处理3k张图片(下载、识别、存储)开50协程比普通循环快200s,100以上速度无明显变化,但超时概率增加,与下载服务器性能有关。

Python数据结构

Posted on 2018-11-05 | In Python
  1. Python手册: https://docs.python.org/3/reference/index.html#reference-index
  2. 数据结构:列表[]、元组()、集合{}、字典{k:v}
  3. 循环技巧:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    # 列表循环技巧:
    for index, value in enumerate(['tic', 'tac', 'toe']):

    # 字典循环技巧:
    knights = {'gallahad': 'the pure', 'robin': 'the brave'}
    for key, value in knights.items():

    #列表打包
    questions = ['name', 'quest', 'favorite color']
    answers = ['lancelot', 'the holy grail', 'blue']
    for q, a in zip(questions, answers):
    print('What is your {0}? It is {1}.'.format(q, a))
  4. 推导式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    # 列表推导式
    squares = [x**2 for x in range(10)]
    mutiSquares = [[row[i] for row in matrix] for i in range(4)] #嵌套的列表推导式

    # 集合推导式
    a = {x for x in 'abracadabra' if x not in 'abc'}
    # >>> {'r', 'd'}

    # 字典推导式
    a = {x: x**2 for x in (2, 4, 6)}
    # >>> {2: 4, 4: 16, 6: 36}
  5. 操作符:

  • not
  • and, or : 参数从左向右解析,一旦结果可以确定就停止

    1
    2
    3
    string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
    non_null = string1 or string2 or string3
    # non_null -> 'Trondheim'
  • in, not in

  • is, is not

可乐项目

Posted on 2018-11-02
  1. * 用于展开/收集元组, ** 用于展开/收集字典
  2. request类库:http://docs.python-requests.org/zh_CN/latest/
  3. 计算图片MD5,如果MD5一致,判断为同一张图片

    1
    2
    3
    4
    5
    6
    7
    def calMD5(url):
    r = requests.get(url)
    imgBytes = r.content
    hl = hashlib.md5()
    hl.update(imgBytes)
    re = hl.hexdigest()
    return re
  4. 异步HTTP库aiohttp: https://hubertroy.gitbooks.io/aiohttp-chinese-documentation/content/

    • 配置ssl证书:
      1
      2
      3
      sslcontext = ssl.create_default_context(cafile='/test.crt')
      async with aiohttp.ClientSession() as session:
      async with session.post('/',data='',ssl_context=sslcontext) as r:
  5. 协程:https://docs.python.org/3/library/asyncio-task.html

    • 控制协程并发数量:
      1
      2
      3
      4
      sema = asyncio.Semaphore(2)
      with (await sema):
      sslcontext........
      async ..........
1…910
Angel Teng

Angel Teng

97 posts
14 categories
37 tags
© 2021 Angel Teng
Powered by Hexo
|
Theme — NexT.Muse v5.1.4