我想在views.py Django 中添加我的脚本

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

我刚刚开始使用 Django 开发 python!我指的是一些视频,他们展示了如何在浏览器上显示内容

在 Views.py 中

  1. 直接使用HttpResponse

代码:

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

代码:

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

但是我有我的Python脚本,即myscript.py(根文件夹) 我如何在 view.py 中运行这个脚本

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

让我们看看我会如何处理这个问题。

#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.