我刚刚开始使用 Django 开发 Python!我指的是一些视频,其中展示了如何在浏览器中显示内容。
在
views.py
...
直接使用
HttpResponse
from django.http import HttpResponse
# Create your views here.
def say_hello(request):
return HttpResponse('Hello')
使用自定义模板 (HTML)
from django.shortcuts import render
# Create your views here.
def say_hello(request):
return render(request, 'hello.html')
我有自己的Python脚本,它是
myscript.py
(在根文件夹中)。
我怎样才能在views.py
中运行这个脚本?
让我们看看我会如何解决这个问题。
#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)