简体   繁体   English

在 django 中运行除 views.py 之外的 python 文件

[英]Running a python file other than views.py in django

I am running a django project and I want to divide up my python code into separate files.我正在运行一个 django 项目,我想将我的 python 代码分成单独的文件。 At the moment I am running my functions from views.py .目前我正在从views.py运行我的功能。 In my views.py I have a plot function.在我的views.py中,我有一个plot function。 I have taken this plotting code and I have created python file called plotting.py which has this plot function in it.我已经使用了这个绘图代码,并创建了名为plotting.py的 python 文件,其中包含这个plot function。 this plotting file lives in the same folder as my views.py此绘图文件与我的views.py位于同一文件夹中

My problem is accessing this plotting.py file.我的问题是访问这个plotting.py文件。 I am trying to access it through from the urls.py by path('plot', plotting.plot), .我正在尝试通过path('plot', plotting.plot),urls.py访问它。 it is not working.它不工作。 Or do I have to link back to a function in views.py and from tat function go to plotting.py`?或者我是否必须在views.py中链接回function and from tat function go to

urls.py should only import views and specify which URL should each view handle. urls.py应该只导入视图并指定每个视图应该处理哪个 URL。 Example:https://docs.djangoproject.com/en/3.0/topics/http/urls/#example示例:https://docs.djangoproject.com/en/3.0/topics/http/urls/#example

Since plot is a function (that probably is plotting something), this needs to go to the view, since it's the view that performs endpoint logic.由于plot是 function (这可能正在绘制一些东西),这需要 go 到视图,因为它是执行端点逻辑的视图。 So you need to import plot in the views file.所以需要在views文件中导入plot

PS: path('plot', plotting.plot) would only work if plotting.plot was a view, but you mentioned it's just a function. PS: path('plot', plotting.plot) plotting.plot) 只有在plotting.plot是一个视图时才有效,但你提到它只是一个 function。

Is this plot function a view where you are returning a response to the client or is this a helper function that you are trying to call from within a view?这是 plot function 是您向客户端返回响应的视图,还是您尝试从视图中调用的助手 function? If it isn't a view, I would recommend adding from.plotting import plot to the top of your views.py file如果不是视图,我建议将from.plotting import plot添加到 views.py 文件的顶部

should you not do from plotting.py import plot and then you can use plot in views.py?你不应该from plotting.py import plot然后你可以在views.py中使用 plot 吗?

If your python version is less then 3.3, you need to create an empty file named __init__.py into the same directory as plotting.py to make your function importable.如果您的 python 版本低于 3.3,则需要在与 plotting.py 相同的目录中创建一个名为__init__.py的空文件,以使您的 function 可导入。

And your plot function must be in function-based view format as demonstrated in django docs: https://docs.djangoproject.com/en/3.0/topics/http/views/#a-simple-view And your plot function must be in function-based view format as demonstrated in django docs: https://docs.djangoproject.com/en/3.0/topics/http/views/#a-simple-view

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

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