简体   繁体   English

如何在Django视图中使用外部Python脚本?

[英]How to use external python script in django views?

If suppose I have a file full of functions in python naming basics.py which does not have a class inside it. 如果假设我在python中命名为basics.py的文件中包含功能齐全的文件, 其中没有类 and there's no __init__() function too. 而且也没有__init __()函数。 Now if I want to access the functions of basics.py inside the views.py . 现在,如果我想在views.py中访问basics.py的功能。 How can I do that? 我怎样才能做到这一点?

use: 采用:

import basics

than use all the functions you want :) 而不是使用您想要的所有功能:)

This is a common mistake because python 3 have stricter rules when it comes to relative imports. 这是一个常见的错误,因为python 3在相对导入方面有更严格的规则。

I assume you have a structure like this. 我假设您具有这样的结构。

myapp
├── basics.py
└── views.py

.. where myapp is in the root of your project. .. myapp在您项目的根目录中。

Let's assume basics.py looks like this. 假设basics.py看起来像这样。

def do_stuff():
    pass

The ways you can import things from basic would then be ( views.py ) 那么,您可以从basic导入内容的方法是( views.py

from myapp import basics
from myapp.basics import do_stuff
from . import basics
from .basics import do_stuff

# View code ...

I assumed here that basics.py and views.py are located in the same package ( app ). 我在这里假设basics.pyviews.py位于同一包( app )中。

When you run a python project your current directory is added to the python path. 当您运行python项目时,当前目录将添加到python路径。 You will either have to import all the way from the root of your project or use . 您要么必须从项目的根目录一直导入,要么使用. to import from the local package/directory. 从本地包/目录导入。

Also notice in the example that you can import the entire module or just single functions/objects. 在示例中还要注意,您可以导入整个模块或仅导入单个功能/对象。 When importing the entire basics module you access it using basics.do_stuff() in the view. 导入整个basics模块时,可以在视图中使用basics.do_stuff()对其进行访问。

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

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