在web上生成Django代码并运行

2024-10-01 02:20:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这对你们很多人来说可能是一个重复的问题,但我还没有找到一个合适的答案。我是Django和Python的初学者。我有一个python代码,它在cli上运行并产生输出,但是我希望相同的程序在web上运行它的输出。在

我读到django是最适合web的框架,为此我开始研究django。我在每个教程中都看到有人讨论过应用程序、视图url等,但没有看到一个将python代码与django集成在一起的例子。在

我所要寻找的是如何将python脚本与Django集成,以及如何将代码放在Django项目或应用程序中。我应该在视图中导入它吗?如果是,那么如何在web上显示我的输出。在

下面是我正在运行的示例代码,它基本上打开两个文件并运行一些regex来提取所需的信息。在

import re


def vipPoolFileOpen():          # function opens vip and pool config file and store them to vip_config and pool_config variables
    with open("pool_config.txt",'rb') as pool_config:
        pool_config = pool_config.read()
        pool_config = pool_config.split('ltm')
    with open("vip_config.txt",'rb') as vip_config:
        vip_config = vip_config.read()
        vip_config = vip_config.split('ltm')
    return vip_config,pool_config



def findWidth(vip_config):  # function to find the maximum length of vip in entire file, this will be used to adjust column space
    colWidth=0
    for item in vip_config:
        i=0
        if colWidth<len(item):
            while i<len(vip_config)-1:
                if len(item)>=len(vip_config[i+1]):
                    colWidth=len(item)
                    i=i+1
                else:
                    i+=1
                    continue
    return colWidth

def regexFunction():
    vip_config, pool_config = vipPoolFileOpen()
    findWidth(vip_config)
    for vip in vip_config:
        regVip = re.compile(r'pool (.+)\r')
        poolByVip = regVip.findall(vip)     # poolByVip holds pool name from the vip_config file
        for poolblock in pool_config:
            regPool = re.compile(r'pool (.+) {')
            poolByConfig = regPool.findall(poolblock)
            if poolByVip == poolByConfig:
                print vip + poolblock
                break
            elif poolByVip == ['none']:
                print vip
                break
            else:
                continue

Tags: anddjango代码inrewebconfiglen
1条回答
网友
1楼 · 发布于 2024-10-01 02:20:35

是的,你应该通过视图把你的输出呈现到网络上。您需要在中编写视图函数(或类视图)视图.py并提供一个你想要的网址网址.py在

如果重写函数以返回所需的结果而不是打印它,则tou可以执行以下操作:

把这个写下来视图.py在

from django.http import HttpResponse
from wherever_you_have_it import regexFunction

def bar(request):
    result = regexFunction()  # result should be a string
    return HttpResponse(result)

在网址.py公司名称:

^{pr2}$

当然,前提是你已经创建了Django应用程序。在

你的结果应该在地址上显示为纯文本本地主机:8000/foo-但你需要:

python menage.py runserver

先到你的候机厅

当然,请随意查看: https://github.com/Ergaro/CheckMyChords 看看一个简单的django应用程序是什么样子的

相关问题 更多 >