在 Django 的 `views.py` 中添加自定义脚本

问题描述 投票:0回答:1

我刚刚开始使用 Django 开发 Python!我指的是一些视频,其中展示了如何在浏览器中显示内容。

views.py
...

  1. 直接使用

    HttpResponse

    from django.http import HttpResponse
    
    # Create your views here.
    def say_hello(request):
        return HttpResponse('Hello')
    
  2. 使用自定义模板 (HTML)

    from django.shortcuts import render
    
    # Create your views here.
    def say_hello(request):
        return render(request, 'hello.html')
    

我有自己的Python脚本,它是

myscript.py
(在根文件夹中)。 我怎样才能在
views.py
中运行这个脚本?

python python-3.x django django-views django-templates
1个回答
1
投票

让我们看看我会如何解决这个问题。

#myscript.py
print("Welcome user!")

我们应该将其更改为这样的:

#myscript.py
def run_script():
   return ("Welcome user!")

然后在你的

views.py
中你必须导入
myscript.py

#views.py
from django.http import HttpResponse
from .script import run_script # Import your script like this

def say_hello(request):
    script_output = run_script()
    # Return the script's output in the HttpResponse
    return HttpResponse(script_output)
© www.soinside.com 2019 - 2024. All rights reserved.