问题描述
该笔记将记录:PyPy 的安装方法,以及常见问题的解决方案。
# Kali GNU/Linux Rolling
#!/bin/sh
apt-get install pypy pypy-dev
#「pypy-dev」:这里面包含一些头文件,需要安装某些模块时使用,而安装「python-dev」是不行的。[……]
问题描述
该笔记将记录:PyPy 的安装方法,以及常见问题的解决方案。
# Kali GNU/Linux Rolling
#!/bin/sh
apt-get install pypy pypy-dev
#「pypy-dev」:这里面包含一些头文件,需要安装某些模块时使用,而安装「python-dev」是不行的。[……]
运行时,禁止产生 pycache 文件
python – Python3 pycache generating even if PYTHONDONTWRITEBYTECODE=1 – Stack Overflow
export PYTHONDONTWRITEBYTECODE=1 # 通过环境变量
当脚本运行结束后,进入交互模式
Enter Interactive Mode In Python
# In Python Script
import code
code.interact(local=locals())
# In Shell
python -i foo.py[……]
[……]
问题描述
包管理器是用于管理 Python 模块的工具,比如搜索模块、安装模块、配置模块、移除模块等等。在 Python 中,有多种类型的包管理器,那我们应该使用那种包管理器呢?本部分将简单整理包管理有关内容,以明确不同场景下应该使用哪种包管理器。
本部分整理常用包,以及对应安装命令。
该笔记将记录:在 Python 中,常用的包(模块)管理工具,以及相关问题的解决办法。
解决方案
pip The PyPA recommended tool for installing Python packages.
setuptools Easily download, build, install, upgrade, and uninstall Python packages
常见问题处理
No module named ‘yaml’:pip3 install pyyaml
No module named ‘ddt’:pip3 install ddt
No module named ‘requests’:pip3 install requests
No module named ‘gi’:视情况而定,有很多名为 gi 的模块。根据错误信息进行判断,我们需要:pip install PyGObject
ImportError: The _imagingft C module is not installed:
# [[https://stackoverflow.com/questions/21233304/python-3-the-imagingft-c-module-is-not-installed |django – Python 3 “The _imagingft C module is not installed” – Stack Overflow]]
sudo pip uninstall pil
sudo rm -rf /usr/local/lib/python3.2/dist-packages/PIL
sudo apt-get install libfreetype6-dev
pip install Pillow[……]
问题描述
现代的高级语言,多数都具有扩展管理工具,以方便开发者安装扩展(插件、类库)。Python 也不例外,它也有自己的模块管理工具:pip
该笔记将记录:在 Python 中,如何使用 pip(1) 安装和管理 Python 模块,以及常见问题处理。
解决方案
第一步、安装命令
安装发行版自带版本(推荐):
# Ubuntu / Debian
apt-get install -y python2-pip
apt-get install -y python3-pip
# 虽然版本较旧,但是经过发行版的完整测试,在当前系统中完全正常工作(几乎很少出问题)
# 如果需要新的版本(或模块),建议使用系统的 pip 创建虚拟环境,然后在虚拟环境中操作
# Centos 7
yum install -y epel-release.noarch yum-config-manager # 添加EPEL库
yum-config-manager –enable epel # 启用仓库
yum install python-pip # 安装命令
安装最新版本:
# pip2 on Ubuntu 20.04 LTS
add-apt-repository universe && apt update && apt-get install -y python2
curl https://bootstrap.pypa.io/get-pip.py –output /tmp/get-pip.py
python2 /tmp/get-pip.py
pip2 –version
第二步、安装模块
# 搜索 PyMySQL 模块
pip search “PyMySQL”
# 安装 PyMySQL 模块
pip install “PyMySQL”
pip install grpcio grpcio-tools
# 使用阿里云加速站点
pip install –index-url https://mirrors.aliyun.com/pypi/simple/ “<pkg-name>”
关于模块搜索:现在(05/31/2021)已经无法使用 pip search “<module name>” 命令进行模块搜索,相关解释参考 Remove the pip search command · Issue #5216 讨论。
常用命令及配置
从文件中读取要安装的模块:
pip install -r requrement.txt
安装离线下载的模块(.whl):
pip ins[……]
问题描述
该笔记将记录:在 PyPy 中,安装 pip 命令。
为什么是「在PyPy中,安装pip命令」?
在PyPy中,它有自己的site-packages路径,因此需要为PyPy单独安装模块。
它不能与Python共享同一个site-packages路径。因此我们需要为PyPy单独安装pip命令。
安装方法
操作系统:Kali GNU/Linux Rolling
# 推荐方法
正常情况下,可以使用pypy -m ensurepip命令进行pip安装,这是推荐的一种方法:
#!/bin/sh
################################################################################
# 使用ensurepip模块
################################################################################
pypy -m ensurepip
################################################################################
# 或者执行如下命令
################################################################################
# pypy
Python 2.7.13 (7.1.1+dfsg-1, Aug 08 2019, 23:50:46)
[PyPy 7.1.1 with GCC 8.3.0] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>>> import ensurepip
>>>> ensurepip.bootstrap(upgrade=True)
使用该方法要求在安装PyPy时,要安装ensurepip模块。
# 手动安装
有时候上面的方法不可能。比如,在Debian/Ubuntu中会出现如下提示:
ensurepip is disabled in Debian/Ubuntu for the system python.
Python modules For the system python are usually handled by dpkg and apt-get.
apt-get install pypy-<module name>
Install[……]
卸载使用 setup.py 安装的应用
python setup.py uninstall – Stack Overflow
python setup.py install –record files.txt
xargs rm -rf < files.txt
参考文献
Building and Distributing Packages with Setuptools — setuptools 54.1.0 documentation[……]
问题描述
在开发 Python 应用时,应用程序经常需要运行在不同版本的环境中、安装不同版本的模块,但是这些模块是相互冲突的、无法共存的。比如,某些 Python 项目运行在 django 2.0 中,而某些 Python 项目运行在 django 3.1 中,我们无法在系统中同时安装两个版本的 django 模块。但是,这是常见需求,很多编程语言都需要面对类似的问题,那要怎么办呢?
在 Python 中,我们可以使用虚拟环境(Virtual Environments)来解决该问题。
该笔记将记录:在 Python 中,如何使用虚拟环境(Virtual Environments)来运行多个不同版本(且独立的)Python 环境,以解决多个项目需要不同版本 Python 环境的问题。
解决方案
虚拟环境(Virtual Environments)
在 Python 中,虚拟环境(Virtual Environments)就是该问题的解决方案。在创建虚拟环境后,相关操作将发生在该环境中(这里“相关操作”是指与 Python 环境有关的操作,比如 pip install 将会将模块安装到该虚拟环境中,而不会影响系统环境),使得单个项目的运行环境与其它项目独立起来。
如下步骤,搭建虚拟环境:
# 第一步、安装 virtualenv 模块
pip3 install virtualenv
# 第二步、创建虚拟环境
virtualenv –python=python3 “venv-example” # 执行该命令,将创建 ./venv-example 目录
# 第三步、激活虚拟环境
source venv-example/bin/activate # 执行该命令后,我们将进入虚拟环境
# 第四步、执行操作
# 与 Python 环境有关的所有操作将发生在该环境中
# 比如,模块安装将安装到 venv-example 下的对应目录中,并在使用时从中加载模块。
# 退出当前虚拟环境
deactivate
virtualenvwrapper – 管理虚拟环境
使用 virtualenv 存在的一个问题是:为了运行不同应用,我们需要为每个应用单独创建虚拟环境。但是,很多应用需要的虚拟环境是相同的,这些完全应用可以共享虚拟环境。因此,我们可以写个工具,用于创建多个虚拟环境,并且能够在这些虚拟执行快速切换。
所幸,现在已经有了这个工具,使用 virtualenvwrapper 工具,便可解决该问题。在安装该工具后,通过命令 mkvirtualenv 将在“共享目录”中创建虚拟环境,通过命令 workon 快速加载特定虚拟环境,当然还有其他功能。
安装并使用 virtualenvwr[……]
问题描述
该笔记将记录:在 Python 中,如何操作常见数据库;
MongoDB
该部分将介绍访问 MongoDB 数据库的方法。在示例中,我们使用 PyMongo 模块:
我们使用 PyMongo 客户端,安装:
#!/bin/sh
pip3 install pymongo
访问项目仓库:http://github.com/mongodb/mongo-python-driver
访问官方文档:https://api.mongodb.com/python/current/api/index.html
我们主要使用 pymongo 文档:https://api.mongodb.com/python/current/api/pymongo/index.html
最常使用 MongoClient 对象:https://api.mongodb.com/python/current/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient
下面只进行简短地介绍,更多内容请参考官方文档;[……]
解决方案
base64
#!/usr/bin/python3
import base64
coded_string = ”’Q5YACgA…”’
plain_text = base64.b64decode(coded_string)
参考文献
Python base64 data decode – Stack Overflow[……]
内容简介
整理发送HTTP(s)请求的库(只因urlib难以记忆)。
Requests: HTTP for Humans
https://requests.readthedocs.io/en/master/
https://github.com/psf/requests/ 12/25/2019 Star 41.1k
使用基础认证
requests.get(‘https://example.com/user’, auth=(‘username’, “password”))
在请求中提交 XML 数据
requests.get(
‘https://example.com’,
headers={‘Content-Type’: ‘application/xml; charset: utf-8’},
data=”<xml_string>”
)
urllib3
https://urllib3.readthedocs.io/en/latest/
https://github.com/urllib3/urllib3 12/25/2019 Star 2.2k
参考文献
Python’s Requests Library (Guide) How can I send an xml body using requests library?[……]
JOSN
How to count items in JSON data Using JSON config files in Python
本文将整理:在 Python 中常用 JSON 操作。
import json
# 字典 => 字符串,顺便美化输出
json_string = json.dumps({
“result”:[{“find”: “true”}]
}, indent=2)
# 字符串 => 字典
json_object = json.loads(json_string)
# 文件 => 字典
json_ojbect = json.load(open(“/path/to/file.txt”))
# 求长度
len(json_object)
XML
xml.etree.ElementTree — The ElementTree XML API Python xml ElementTree from a string source?
在 Python 中,与 XML 有关的操作,以及相关问题的解决办法。
# 导入模块
import xml.etree.ElementTree as ET
# 读取XML数据
tree = ET.parse(“/path/to/foo.xml”)
tree = ET.fromstring(xml_string)
# 修改数据
for item in tree.iter(“item”):
item.text = “some text”
tree.write(“/path/to/bar.xml”)
# 打印XML数据
xml_string = tree.tosting()[……]
问题描述
该笔记将记录:在 Python 中,如何进行日志打印,以及常见问题处理。
解决方案
简单示例:
import logging
logging.basicConfig(encoding=’utf-8′, level=logging.DEBUG)
logging.debug(‘This message should go to the log file’)
logging.info(‘So should this’)
logging.warning(‘And this, too’)
logging.error(‘And non-ASCII stuff, too, like Øresund and Malmö’)
彩色日志打印:
#!/usr/bin/python3
# pip install coloredlogs
# 简单示例
import coloredlogs, logging
coloredlogs.install()
logging.info(“It works!”) # 2014-07-30 21:21:26 peter-macbook root[7471] INFO It works!
# 特定 Logger 设置
logger = logging.getLogger(__name__)
coloredlogs.install(level=’DEBUG’, logger=logger) # a specific logger object
logger.debug(“this is a debugging message”)
logger.info(“this is an informational message”)
logger.warning(“this is a warning message”)
logger.error(“this is an error message”)
logger.critical(“this is a critical message”)
参考文献
Logging HOWTO — Python 3.9.2 documentation How can I color Python logging output? – Stack Overflow xolox/python-coloredlogs: Colored terminal output for Python’s logging module[……]
内容简介
本部分整理与Qt相关的内容。但是目前Python是我的主要方向,所以本部分的绝大多数内容都是与Qt的Python API相关的技术。也会涉及一些Qt的基本概念,毕竟基础原理是要懂得。
参考文献
Wikipedia/Qt (software) GitHub/Qt[……]
内容简介
本部分介绍在Python的Qt中如何处理信号与槽。
基本概念
# Slot
响应于特定信号而被调用的函数,所以本质上还是函数。在Qt中的Widget有许多预定义的slot,但通常的做法是将Widget子类化,并添加自己的slot,以便可以处理感兴趣的信号。
# Signal
当对象的内部状态发生更改时,对象会发出Signal。Signal是公共访问函数,所以说Signal还是函数,可以从任何地方发出,但官方建议只从定义信号及其子类的类中发出。
简单示例
下面是一个及其简单的示例:
# 在按钮点击的时候,触发内部的slot_method方法
# 行话:clicked信号被连接到slot_method槽。当发出clicked信号时,将执行slot_method方法。
m_button.clicked.connect(self.slot_method)
参考文献
PyQt5 signals and slots Support for Signals and Slots Qt 5.13 / Qt WebEngine / C++ Classes / QWebEngineView PySide/PyQt Tutorial: Creating Your Own Signals and Slots PyQt – Signals & Slots Qt 5.13 / Qt Core / Signals & Slots[……]
内容简介
本部分简单介绍与PyQt及PySide这两个库的区别,以及相关的内容。
# Qt for Python (PySide2)
简述
「Qt for Python」是一个项目,由Qt官方提供,它提供Qt的Python绑定,可以使用Python语言创建Qt程序。
安装
如果要在Python中使用「Qt for Python」项目,则安装PySide2模块即可。
教程
Python Qt tutorial
PyQt – PyQt4 for Qt v4 / PyQt5 for Qt v5
简述
与「Qt for Python」作用类似,向Python中暴露Qt接口,可以使用Python语言开发Qt应用程序。
安装
如果要在Python中使用PyQt模块,则安装PyQt4或者PyQt5模块即可,并且还包含一些其他的模块,可能需要单独安装。比如安装「WebEngine」模块,执行pip install PyQtWebEngine=5.13.0命令,同时它也会安装PyQt5等相关的模块。
教程
Qt for Python/Tutorial
文档
PyQt v5.13 Reference Guide
对比总结
在WebEngine方面,与PyQt5相比,PySide2覆盖的API较少,因此在进行WebEngine编程时,推荐使用PyQt5模块。
参考文献
Qt for Python – The official Python bindings for Qt. What is PyQt?[……]
内容简介
本文简单整理QApplication, QGuiAppication, QCoreApplication这三个对象之间的区别。
# QCoreApplication
基类。在命令行应用程序中,应该使用它。
# QGuiApplication
基类 + GUI功能。在QML应用程序中,应该使用它。「QML」是一种用户界面标记语言,是一种指令使的语言,与CSS有些相似。
# QApplication
基类 + GUI + 对Widget支持。在QtWidgets应用程序中,应该使用它。
# Event loop
字面上翻译就是「事件循环」,详细的解释需要阅读文档和一些Qt相关的书籍。但简而说:事件循环是一个无限循环,它在应用程序的后台运行,处理从操作系统传入的事件(鼠标移动,点击,绘制事件,硬件事件等)以及内部通信(信号和插槽)。调用app.exec()时,事件循环开始,这也是“在执行app.exec()后,后续代码不会再继续执行”的原因。
参考文献
differences between QApplication, QGuiAppication, QCoreApplication classes[……]
内容简介
本部分介绍QtWebKit以及QtWebEngine相关的技术。但是,本文更侧重于QtWebEngine技术,因为在Qt5.6中移除了QtWebKit模块。
另外,本部分的内容更侧重于爬虫,因为这些技术是在写爬虫的时候才学习的(反爬虫技术再牛,也得让用户可以正常访问,不是么?那……我们就做一个正常的用户)。
# QtWebKit and Qt WebEngine
根据官方所述「QtWebKit got deprecated upstream in Qt 5.5 and removed in 5.6」,所以从后面开始,我们整体基于QtWebEngine展开,极少涉及与QtWebKit相关的技术。
# 官方文档
不管是PyQt还是PySide模块,它们的文档都不够详尽。而PySide的文档明显是从Qt的文档里复制过来的。
如果要使用这些API库:「详细描述」还要参考Qt官方文档,但是「函数参数类型」可以参考这些文档。
Qt for Python/WebEngine
PySide2.QtWebEngineWidgets
Qt WebEngine Debugging and Profiling
# PyQt5
PyQt v5.13 Reference Guide / QtWebEngineWidgets
# 使用WebEngine构建应用
import sys
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
web = QWebEngineView()
web.load(QUrl(“https://www.example.com”))
web.show()
sys.exit(app.exec())
附加说明
# Get Html element value with QWebEngine 在QtWebEngine中,如果要获取页面的元素,需要通过QWebEnginePage的runJavaScript方法。
# Missing methods for QWebEnginePage with QWebEngineCallback 在PySide2中,没有toHtml方法。
相关示例
# WebEngine Quick Nano Browser 使用QML语言创建一个浏览器。
# WebEngine Content Manipulation Example 向页面中注入JQuery[……]
内容简介
本部分整理与Qt有关的杂记。
# Qt Creator 、Qt Designer、Qt Quick Designer
-「Wikipedia/Qt Creator#Editors」 -「Qt Designer vs Qt Quick Designer vs Qt Creator?」
Qt Creator是Qt的IDE,它大大简化了Qt的开发。
Qt Designer是一个图形工具,可以让您构建QWidget GUI。
Qt Quick Designer与Qt Designer类似,但用于构建基于QML的GUI。
Qt Quick Designer与Qt Designer两者都内置于Qt Creator。
# 安装Qt Creator工具
#!/bin/sh
################################################################################
# Kali GNU/Linux Rolling
#
# # Ubuntu 14.04 QtCreator Qt5 examples missing
# # https://askubuntu.com/questions/450983/ubuntu-14-04-qtcreator-qt5-examples-missing
# # Getting Started With Qt and Qt Creator on Linux
# # https://www.ics.com/blog/getting-started-qt-and-qt-creator-linux
#
################################################################################
# 安装基础
apt-get install qtcreator
# 安装示例(不同的示例可能在不同的包中),该命令并未安装说有的示例包。
apt-get install qtbase5-examples qtbase5-doc-html qtwebengine5-examples
# 使TabWidget按钮居中
-「QTabwidget’s tab text alignment not working」
# 创建按钮
QLabel * button = new QLabel(“text”);
button->setAlignment(Qt::AlignLeft);
# 将原有的文本置空
ui->tabWidget->tabBar()->setTabText(index, “”);
#[……]
Paramiko 是 Python 实现 SSHv2 协议的模块,它支持口令认证和公钥认证两种方式。我们能够基于Paramiko模块编写Python代码,实现SSH相关功能。
它可以实现安全的远程命令执行、文件传输等功能。
组件架构(架构概述)
Paramiko 组件如下图所示,最常用的两个类为 SSHClient 类和 SFTPClient 类,分别提供 SSH 和 SFTP 功能。
我们将主要学习四个类的相关方法:Transport类,Key handling类,SSHClient类,SFTPClient类;
常用协议类
Channel:该类用于创建在 SSH Transport 上的安全通道。Channel类包含执行命令,请求X11会话,发送数据,打开交互式会话等方法。通常这些来自Channel类的常用方法已包装在 SSHClient 中。
Message:SSH Message是字节流,该类包含向流中写入字节,提取字节等方法。该类对字符串、整数、bools、无限精度整数(Python中称为long)的某些组合进行编码。
Packetizer:数据包处理类。Packetizer类包含检查握手,获取channel ID等方法。
Transport:该类用于在现有套接字或类套接字对象上创建一个Transport会话对象。Transport类包含公钥认证,打开channel通道等方法。
SFTPClient:该类通过一个打开的SSH Transport会话创建SFTP会话通道并执行远程文件操作。SSHClient类包含建立连接,打开交互式会话等方法。
SSHClient:SSHClient类是与SSH服务器会话的高级表示。该类集成了Transport,Channel和SFTPClient类。SFTPClient类包含文件上传,文件下载等方法。
密钥相关类
SSH Agent类:该类用于SSH代理。
Host keys类:该类与OpenSSH known_hosts文件相关,用于创建一个host keys对象。
Key handling类:该类用于创建对应密钥类型的实例,如RSA密钥,DSS(DSA)密钥。
Transport 及其方法介绍
一个SSH Transport连接到一个流(通常为套接字),协商加密会话,进行认证。后续可在加密会话上创建通道。多个通道可以在单个会话连接中多路复用(事实上经常如此,如端口转发)。
如下为方法示例:
tran = paramiko.Transport((‘192.168.56.100’,22))
tran.connect(username=‘client’,p[……]
参考文献
Calling an external command in Python subprocess — Subprocess management[……]
问题描述
在编写 Python 工具时,我们经常需要解析命令行参数,以获取输入数据。
该笔记将记录:在 Python 中,如何解析命令行参数的方法(比如,使用模块 getopt 解析命令行参数),以及相关问题处理。
解决方案
通过 argparse 模块
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(“–host”, default=”0.0.0.0″, help=”Exporter listen address”)
parser.add_argument(“–port”, default=”9349″, help=”Exporter listen port”)
args = parser.parse_args()
print ‘Query string:’, args
注意事项:在 Python 2.7- 中,使用 optparse 模块。
通过 getopt 模块
使用示例:
import getopt, sys
try:
opts, args = getopt.getopt(sys.argv[1:], “hc:”, [“help”,”config-file=”])
except getopt.GetoptError:
print(“error message”)
sys.exit(1)
for opt, arg in opts:
if opt == “-h”:
# doing some stuff
elif opt in (“-h”, “–config-file”):
# doing some stuff
else:
# doing some stuff
参考文献
Python 命令行参数 python – What’s the best way to parse command line arguments? – Stack Overflow Argparse Tutorial — Python 3.9.2 documentation python – Argparse: Required arguments listed under “optional arguments”? – Stack Overflow[……]
问题描述
该笔记将记录:在学习 Django 过程中而产生的学习笔记,以及相关问题的解决办法。
解决方案
参考 Django/Writing your first Django app, part 1 文档,我们开始进行 Django 的初识与学习。
针对该笔记及其子章节,其主要内容是对官方文档的学习与摘率,包括相关问题的解决方案。
P1 创建应用的基本步骤
python – How to check Django version – Stack Overflow FAQ: Installation | Django documentation | Django windows – Django, can’t create app in subfolder – Stack Overflow
参考 Writing your first Django app, part 1 文档,以进行快速入门,通过该文档能够让我们对整个框架的 使用方法、目录结构、路由模式、运行方法 形成基础认识。
创建项目(PROJECT),创建应用(APPLICATION),运行服务,获得能够快速访问的 Web 应用;
// —————————————————————————- # 版本选择
Django version Python versions
2.2 3.5, 3.6, 3.7, 3.8 (added in 2.2.8), 3.9 (added in 2.2.17)
3.0 3.6, 3.7, 3.8, 3.9 (added in 3.0.11)
3.1 3.6, 3.7, 3.8, 3.9 (added in 3.1.3)
3.2 3.6, 3.7, 3.8, 3.9, 3.10 (added in 3.2.9)
4.0 3.8, 3.9, 3.10
// —————————————————————————- # 第一步、安装框架
# pip3 install Django==3.2.13 # 我们当前使用的版本
# python3 -m django –version # 查看当前安装版本
# ./manage.py –version[……]
解决方案
参考 Writing your first Django app, part 3 文档,以获取在 Django 中使用视图及模板的方法。
在 views.py 中: 进行相关的业务逻辑处理, 并使用 HttpResponse() 来显示页面,或使用 render() 来显示页面; 通过 Http404() 或 get_object_or_404() 进行相关错误处理;
在 template/<app-name>/ 中,添加相关模板文件; 并在模板文件中使用模板语言来显示页面; 通过 url() 的 name 参数定义的名称来引用地址,以防止硬编码; 通过命名空间的方式来定义和引用 URL 防止出现命名冲突的情况;
常见问题
注入变量到所有模板
python – Django – How to make a variable available to all templates? – Stack Overflow
1)Add custom_app to INSTALLED_APPS in settings.py (you’ve done it already, right?);
2)Create a context_processors.py into custom_app folder;
3)Add the following code to that new file:
def categories_processor(request): # request 参数是必须的
categories = Category.objects.all()
return {‘categories’: categories}
4)Add context_processors.py to TEMPLATE_CONTEXT_PROCESSORS in settings.py
TEMPLATE_CONTEXT_PROCESSORS += (“custom_app.context_processors.categories_processor”, )
5)And now you can use {{categories}} in all the templates
关闭 HTML 转义
django – Rendering a template variable as HTML – Stack Overflow
// 默认 HTML 转义,我们需要关闭 HTML 转义;
{{ myhtml |safe }}
{% autoescape o[……]
问题描述
当应用程序的运行时,需要指定不同的配置信息或参数,以来控制应用程序的运行。
该笔记将记录:在 Django 中,如何管理配置文件;
解决方案
在 Django 中,通过 Django settings 来完成应用程序的应用控制:
参考官方文档,以获取通过配置文件来控制系统运行的方法: 1)2.2 / Settings 2)4.0 / Settings | Django documentation | Django
补充说明
除此之外,也能够通过其他模块来进行配置处理,例如 ConfigParser 模块:
# https://stackoverflow.com/questions/12750778/booleans-in-configparser-always-return-true
print config.getboolean(‘main’, ‘some_boolean’)
但非 Django 内置的配置方法不是我们关注的重点,我们更倾向于使用框架内置的工具和方法。
配置文件管理方法
python – Is this approach to Django multiple settings files reasonable? – Stack Overflow Django Tips #20 Working With Multiple Settings Modules
如上文档,提到多种配置文件的管理方法。如下是我们从其中借鉴方法:
settings
├── __init__.py
├── defaults.py
├── dev.py
└── production.py
// —————————————————————————- // settings/__init__.py
from dev import *
// —————————————————————————- // settings/dev.py
# Load defaults in order to then add/override with dev-only settings
from defaults import *
DEBUG = True
# … etc.
// —————————————————————————- // settings/produc[……]
问题描述
我们经常使用 Python 语言,但是多半是用作批处理和脚本任务,从未写过任何 Web 应用,这可能与我们的工作内容相关。
现在,我们需要使用 Flask 编写应用(实际上是有个项目是 Flask 框架开发的,现在我们需要修改这个项目),所以要开始学习新技术,Flask 框架。
该笔记将记录:使用 Flask 框架编写应用的示例(入门级)以及常见问题处理,后续将不断的补充相关内容。
解决方案
入门的简单示例
官方首页给的示例也是相当简单的,但是足以说明问题,我们很快就能得到能够运行的 Web 应用:
编写 helloworld.py 文件:
from flask import Flask, escape, request
app = Flask(__name__)
@app.route(‘/’)
def hello():
name = request.args.get(“name”, “World”)
return f’Hello, {escape(name)}!’
if __name__ == “__main__”:
app.run(debug=True)
然后,运行该应用:
# python /tmp/demo.py
* Serving Flask app “demo” (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 249-201-688
最后,访问该应用程序:
# curl http://127.0.0.1:5000/
Hello, World!
参考文献
Flask | The Pallets Projects[……]
作为一个Python菜鸡,有些常用的代码和方法还是要整理一下的:
#!python3
################################################################################################################################################################
# 多行代码可以使用反斜线,一种经典的做法
################################################################################################################################################################
################################################################################################################################################################
# 打印字典或者数组什么的
# https://stackoverflow.com/questions/15785719/how-to-print-a-dictionary-line-by-line-in-python
################################################################################################################################################################
print(json.dumps(dicObject, indent = 4, ensure_ascii=False)) # 并显示UNICODE字符,而不时是转义序列
################################################################################################################################################################
# Python String endswith() Method
# https://www.tutorialspoint.com/python/string_endswith
###################################[……]
获取网络信息
Python Get Default Gateway IP Using Netifaces: A Step Guide – Python Tutorial python – How to get the physical interface IP address from an interface – Stack Overflow
pip install netifaces
import netifaces
获取网关设备及地址:
# gets gateway of the network
gws = netifaces.gateways()
gateway = gws[‘default’][netifaces.AF_INET][0] # 默认网关地址
gateway_interface = gws[‘default’][netifaces.AF_INET][1] # 默认网关接口名称
获取网卡的地址:
address = netifaces.ifaddresses(“interface_name”)[netifaces.AF_INET][0][‘addr’][……]
问题描述
对开发中遇到的错误进行汇总。
TypeError: ‘module’ object is not callable
问题描述:在 Dajngo 中,我们遇到该错误。注意,还有很多其他原因会到导致该问题。
原因分析:我们使用的 Django 不支持更新的 Celery 版本,进而 Celery 注解导致该错误。
解决方案:Celery 版本降级,指用 Django 支持的版本;
# file=sys.stderr)
File “/usr/lib/python3.5/site.py”, line 182
file=sys.stderr)
^
SyntaxError: invalid syntax
版本:Python3.5 描述:在Python3.5脚本中使用os.system调用了一个python2.7的命令,产生了如上错误。是在Eclipse中直接运行Python3.5脚本。 解决:抱着试一试的态度,我在终端中直接运行了脚本,是正常的,没有上述错误。难道是Eclipse导致的BUG?在Eclipse中安装了PyDev插件。
ImportError: No module named ‘encodings’
python – ImportError: No module named ‘encodings’ – Stack Overflow
问题描述
在执行虚拟环境时,出现如下错误:
…
Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named ‘encodings’
…
原因分析
我们原本使用 Python 3.7 创建虚拟环境,迁移到使用 Python 3.9 新主机而出现该错误。
我们没有找到具体原因,我们推测是因为新环境缺少某些模块。
解决方案
我们将重建虚拟环境: 1)pip freeze > requirements.txt 2)然后,使用 virtualenv 重新基于 Python 3.9 的创建虚拟环境,并激活; 3)pip install -r requir[……]
内容简介
处理ImportError: bad magic number in ‘xxxx’错误。
问题描述
执行Python脚本,提示ImportError: bad magic number in ‘xxxx’错误。
问题原因
在项目中包含一些.pyc文件,这其中包含了一些之前的版本信息和日期时间。删除这些文件即可。
解决办法
在项目的根目录中执行:
#!/bin/sh
find . -name “*.pyc” -exec rm -f {} \;
参考文献
ImportError: bad magic number in ‘time’: b’\x03\xf3\r\n’ in django[……]