django - reusing functions in many views

落花浮王杯 提交于 2020-01-02 19:37:11

问题


I have a bunch of functions that I created in some views that must be reused in many other views. Do I need to create a class and put those functions in a class? If yes how exactly has to be done in Django and then how do I call and initiate them in the new views?


回答1:


Django views are just Python functions. You can call other Python functions from them just as you can from any other Python code. Put your functions into a .py file, import it, and invoke the functions.

Of course, it may make sense for other reasons to create a class to hold the functions, but you certainly don't need to in order to call them from views.




回答2:


The solution would be to create the myfunctions.py file in your app folder and import it in your views. Your views file would look like:

import myfunctions

def my_view(request):
    .....
    foo = myfunctions.bar()
    ....



回答3:


From my point of view, if you have a lot of functions that are widely used in your project it make sense put all this in some separate application. I create some module named 'contrib' for this purposes. It can avoid some time for maintaining this code in future




回答4:


You look to complicated to Django. Django is just another Python application and lives in the Python world. For example you can create file library.py and import this file where is needed (in modules where the function from library is needed). If you need you library's functions to get data from database, just import models in the library.py and use them.

Django doesn't have such a big think as "module". You creating the architecture, you can define what in your case is module. In general this is just simple directory with init.py file inside to be able to import files from there.

Hope that helped.



来源:https://stackoverflow.com/questions/4909473/django-reusing-functions-in-many-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!