普通视图

发现新文章,点击刷新页面。
昨天以前首页

django 直接运行目录下py 文件

2025年1月7日 10:16

为了处理数据,直接写了一个文件用来处理解析数据。然而比较诡异的一点是,使用 pycharm 可以直接运行这个文件,不会报错。但是,如果用命令运行就直接报错了。

上面是 pycharm 的运行效果,下面是直接命令运行的效果。

(venv) PS E:\Pycharm_Projects\powersystem> E:\Pycharm_Projects\powersystem\venv\Scripts\python.exe E:\Pycharm_Projects\powersystem\application\data_process_test.py 
Traceback (most recent call last):
  File "E:\Pycharm_Projects\powersystem\application\data_process_test.py", line 17, in <module>
    django.setup()
  File "E:\Pycharm_Projects\powersystem\venv\lib\site-packages\django\__init__.py", line 19, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "E:\Pycharm_Projects\powersystem\venv\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__
    self._setup(name)
  File "E:\Pycharm_Projects\powersystem\venv\lib\site-packages\django\conf\__init__.py", line 69, in _setup
    self._wrapped = Settings(settings_module)
  File "E:\Pycharm_Projects\powersystem\venv\lib\site-packages\django\conf\__init__.py", line 170, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "G:\Python3.10.6\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'application'

提示的错误信息是找不到 application,但是这个文件是作为 django 的一部分存在的,按理也不需要去设置什么东西。之前的时候不能运行也就算了,但是现在有台服务器在内网,无法链接内网的的数据库进行数据处理,这就比较麻烦。

不过既然 pycharm 能运行,那肯定是有些东西不一样,猜测是 pycharm 将当前的目录加入 lib 目录了。添加下面的代码重新运行。

import os,sys

if __name__ == '__main__':
    # 获取当前脚本所在目录的绝对路径
    current_directory = os.path.abspath(os.path.dirname(__file__))

    # 将当前目录添加到sys.path
    sys.path.append("E:/Pycharm_Projects/powersystem/")
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "application.settings")
    import django

    django.setup()
    label =get_device_label(msg['devvar'])
    new_msg = rebuild_msg(msg, label)
    print(new_msg)

现在一切就 ok 了。

其他的运行脚本方式:

https://django-extensions-zh.readthedocs.io/zh-cn/latest/runscript.html

https://www.jb51.net/article/236739.htm

Django 打包为 docker 镜像

2024年11月25日 13:51

之前也想过将 django 项目打包成 docker 部署,但是由于之前的项目过于庞大,用到了系统的定时任务等各种系统服务,不知道打包成 docker 之后相关的服务是否依然能够启动,所以并未实施。

前几天做的我的足迹地图,项目相对来说比较独立,没有其他的依赖项,正好可以尝试一下。

首先在项目下创建 Dockerfile,写入以下内容:

# 使用官方Python运行时作为父镜像
FROM python:3.8.18-slim

# 设置工作目录
WORKDIR /app

# 将当前目录内容复制到位于/app中的容器中
COPY . /app


# 安装项目依赖
RUN pip install --no-cache-dir -r requirements.pip -i https://pypi.tuna.tsinghua.edu.cn/simple

# 暴露端口8000,与Django的默认运行端口一致
EXPOSE 10086

# 定义环境变量
ENV NAME=Django

# 在容器启动时运行Django的manage.py命令
CMD ["python", "manage.py", "runserver", "0.0.0.0:10086"]

网上代码来回抄,第二行都是FROM python:3.8-slim 如果这么写会导致下面的错误:

PS E:\Pycharm_Projects\BabyFootprintV2> docker build -t baby-footprint:1.0 .
[+] Building 21.2s (2/2) FINISHED docker:desktop-linux
 => [internal] load build definition from Dockerfile 0.0s
 => => transferring dockerfile: 568B 0.0s
 => ERROR [internal] load metadata for docker.io/library/python:3.8-slim 21.1s
------
 > [internal] load metadata for docker.io/library/python:3.8-slim:
------
Dockerfile:2
--------------------
   1 | # 使用官方Python运行时作为父镜像
   2 | >>> FROM python:3.8-slim
   3 |
   4 | # 设置工作目录
--------------------
ERROR: failed to solve: python:3.8-slim: failed to resolve source metadata for docker.io/library/python:3.8-slim: failed to do request: Head "https://registry-1.docker.io/v2/library/python/manifests/3.8-slim": dialing registry-1.docker.io:443 container via direct connection because has no HTTPS proxy: connecting to registry-1.docker.io:443: dial tcp 69.63.186.31:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

直接访问上面的网址docker.io/library/python:3.8-slim会发现根本没这么东西,所以要改成FROM python:3.8.18-slim

搜索一下,会有教程提示先下载 python3.8的 docker:

PS E:\Pycharm_Projects\BabyFootprintV2> docker pull python:3.8.18-slim
3.8.18-slim: Pulling from library/python
8a1e25ce7c4f: Pull complete
1103112ebfc4: Pull complete
b7d41b19b655: Pull complete
6a1ad0671ce8: Pull complete
de92c59aadaa: Pull complete
Digest: sha256:e796941013b10bb53a0924d8705485a1afe654bbbc6fe71d32509101e44b6414
Status: Downloaded newer image for python:3.8.18-slim
docker.io/library/python:3.8.18-slim

3.8.18是 ok 的,此时重新 build 即可:

PS E:\Pycharm_Projects\BabyFootprintV2> docker build -t baby-footprint:1.0 .
[+] Building 214.6s (9/9) FINISHED docker:desktop-linux
 => [internal] load build definition from Dockerfile 0.0s
 => => transferring dockerfile: 571B 0.0s
 => [internal] load metadata for docker.io/library/python:3.8.18-slim 0.0s
 => [internal] load .dockerignore 0.0s
 => => transferring context: 2B 0.0s
 => [1/4] FROM docker.io/library/python:3.8.18-slim 0.1s
 => [internal] load build context 0.9s
 => => transferring context: 43.30MB 0.8s
 => [2/4] WORKDIR /app 0.1s
 => [3/4] COPY . /app 0.2s
 => [4/4] RUN pip install --no-cache-dir -r requirements.pip -i https://pypi.tuna.tsinghua.edu.cn/simple 212.0s
 => exporting to image 1.4s
 => => exporting layers 1.4s
 => => writing image sha256:cba073b574f88f19be7487b29612e19b9826ab99e7b54ea748bd5df22e83e1a0 0.0s
 => => naming to docker.io/library/baby-footprint:1.0 0.0s

编译变成,就可以像 docker hub 推送镜像了,不过首先需要设置 tag,如果直接推送会提示下面的错误:

PS E:\Pycharm_Projects\BabyFootprintV2> docker push baby-footprint:1.0
The push refers to repository [docker.io/library/baby-footprint]
04013169f44d: Preparing
f7c443286fad: Retrying in 5 seconds
fd749af069d5: Retrying in 5 seconds
3482d4cd60de: Retrying in 5 seconds
370c0e78e3ea: Retrying in 5 seconds
a74bee0a48a5: Waiting
c8f253aef560: Waiting
a483da8ab3e9: Waiting
denied: requested access to the resource is denied

这个提示也比较坑人,由于 docker 被屏蔽,我一直以为是网络连接问题,直到后来才发现是路径问题。

通过下面的命令设置 tag 后 push:

docker tag baby-footprint:1.0 obaby/baby-footprint:1.0
PS E:\Pycharm_Projects\BabyFootprintV2> docker push obaby/baby-footprint:1.0
The push refers to repository [docker.io/obaby/baby-footprint]
04013169f44d: Pushed
f7c443286fad: Pushed
fd749af069d5: Pushed
3482d4cd60de: Pushed
370c0e78e3ea: Layer already exists
a74bee0a48a5: Pushed
c8f253aef560: Pushed
a483da8ab3e9: Layer already exists
1.0: digest: sha256:0d0c0989a64cc3f3e192e5c8e7bc4931676d49ab66d810061a1daec6b1a6af58 size: 2000

受限于网络问题,可能会 push 失败,多重试几次就 ok 了。

最后就可以直接 docker 安装运行啦:

docker push obaby/baby-footprint:tagname

姐姐,你也不想让别人知道你的秘密吧? — 浅谈 Python 代码加密

2024年8月23日 11:13

像 python 这种非编译型的语言,在代码加密上有这先天性的弱势,虽然java 之类的编译成 jar 依然比较容易反编译回来,但是毕竟也算是提升了那么一点点门槛,再加上混淆神马的,基本就能避免一些入门级的破解了。

但是对于 python 这种,如果发布不想直接让别人看代码,最简单的办法就是打包成二进制。通常的做法就是 py2exe.

官网地址:https://www.py2exe.org

py2exe

py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.Spice

Development is hosted on GitHub. You can find the mailing listsvn, and downloads for Python 2 there. Downloads for Python 3 are on PyPI.

py2exe was originally developed by Thomas Heller who still makes contributions. Jimmy Retzlaff, Mark Hammond, and Alberto Sottile have also made contributions. Code contributions are always welcome from the community and many people provide invaluable help on the mailing list and the Wiki.

py2exe is used by BitTorrentSpamBayes, and thousands more – py2exe averages over 5,000 downloads per month.

In an effort to limit Wiki spam, this front page is not editable. Feel free to edit other pages with content relevant to py2exe. You will need an account to edit (but not to read) and your account information will be used only for the purposes of administering this Wiki.

The old py2exe web site is still available until that information has found its way into this wiki.

之前发布的各种美女爬虫基本都是通过 py2exe 打包的,虽然体积比较大,但是整体来说效果还算不错。

但是对于 web 框架,例如 flask django 之类的该怎么打包?这个就稍显麻烦一些了。

搜索一下,也能找到一些工具,例如 https://github.com/amchii/encryptpy 这个东西底层还是通过 cython 来实现的,如果不想使用这个工具,那么直接使用 cython 也是可以的,至于原理,本质上是直接把 py代码编译成了二进制文件。

下面直接用 cython 来实现:

pip install cython

编写编译脚本,叫什么无所谓,这里我的名称是cython_build.py:

from distutils.core import setup
from Cython.Build import cythonize

setup(
    ext_modules=cythonize(["application/settings.py",
                           "PowerManagement/models.py",
                           "PowerManagement/views/meter.py",
                           "PowerManagement/views/meter_remote.py",
                           "PowerManagement/views/substation_picture.py",
                           "PowerManagement/views/circuit.py",
                           ])
)

建议将上面的代码放在项目的根目录下,要处理的 modules 使用相对路径来实现。

通过下面的命令编译 py 文件:

python3 cython_build.py build_ext --inplace

但是上面的代码有个问题,那就是–inplace 并没有吧所有的 so文件放到原来的目录下,编译之后,一些文件放到了项目根目录下:

扩展名为 so 的文件就是编译生成的二进制文件,此时如果直接运行项目会提示各种组件找不到,还需要将处理后的文件复制到原来的目录下:

mv *.so PowerManagement/views/

最后一步就是删除原来的 py 文件:

cd "PowerManagement/views/"
rm  *.py

到这里整个编译流程就算完成了,可以尝试重新启动服务了。

毕竟姐姐,你也不想你的代码被人随便给抄走吧?

❌
❌