简体   繁体   English

在 Django 项目中放置外部 python 脚本的位置?

[英]Where to place external python scripts in a Django project?

Where someone should place any external python script for her Django project?有人应该在哪里为她的 Django 项目放置任何外部 python 脚本? What is the more appropriate location (if any)?什么是更合适的位置(如果有的话)? Shall she create a folder in the main Django project and put it there and add this to the python path or is there a better way to deal with this issue?她应该在主 Django 项目中创建一个文件夹并将其放在那里并将其添加到 python 路径中还是有更好的方法来处理这个问题? The reason for external scripts is not to overload the views with code that can be better organized in script files and can serve more than one views.使用外部脚本的原因是不要使用可以在脚本文件中更好地组织并且可以为多个视图提供服务的代码来重载视图。

Create a folder, say utils, and make it a module by creating __init__.py inside it.创建一个文件夹,比如 utils,并通过在其中创建__init__.py使其成为模块。 Now create any script under this folder.现在在此文件夹下创建任何脚本。 Let's say you have a file called utils.py that contains some of your python code and you want to import it.假设您有一个名为 utils.py 的文件,其中包含您的一些 Python 代码并且您想要导入它。

Wherever you want to import then import your python script like无论您想导入哪里,然后导入您的 python 脚本,如

from utils.utils import YourClassOrFunction

You can have additional files that have generic code in their own files and just import them when you need them for your views, or whatever.您可以拥有其他文件,这些文件在它们自己的文件中具有通用代码,并且只需在您的视图或其他任何需要它们时导入它们。 If they are only going to be used in one app, then just put them in that apps folder.如果它们只在一个应用程序中使用,那么只需将它们放在该应用程序文件夹中。 If they are more generic then you can put them in a file or folder that isn't part of any particular app.如果它们更通用,那么您可以将它们放在不属于任何特定应用程序的文件或文件夹中。

Django does some magic with files and folders it expects to exist, but you can put other files wherever you want it works like any other Python project. Django 对它期望存在的文件和文件夹做了一些魔法,但是你可以把其他文件放在任何你想要的地方,就像任何其他 Python 项目一样。

Adding project path should be done at your manage.py , but if you wanted to do something before your request reached views.py you can use middlewares .添加项目路径应该在您的manage.py完成,但是如果您想在请求到达views.py之前做一些事情,您可以使用middlewares https://docs.djangoproject.com/en/1.8/topics/http/middleware/ https://docs.djangoproject.com/en/1.8/topics/http/middleware/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM