Django + MySQL,创建MySQL查询以传递有效参数到URL

0 投票
3 回答
1383 浏览
提问于 2025-04-17 22:09

我刚接触Django,需要一些帮助。我想用Django(版本1.4)来制作一个库存工具,这个工具可以轻松地从数据库(MySQL)中获取主机/服务器的列表。

我想要实现的功能是,简单地通过URL传递主机名作为参数,然后在Django应用中获取这个主机名,构建查询,并将结果显示在用户界面上。

举个例子,URL可以是这样的:http://test.example.com/gethost/?hostname=localhost

== urls.py:

urlpatterns = patterns('',
    # Examples:
    url(r'^gethost', 'dc.views.gethost', name='gethost'),

== views.py:

def gethost(request, hostname, template_file="gethost.html"):
  from django.db import connection, transaction
  hostname = request.GET.get('hostname')
  cursor = connection.cursor()
  cursor.execute("SELECT * FROM inventory WHERE hosts='%s'" % 'hostname')
  rows = cursor.fetchall()
  t = Context({'results': rows})
  return render_to_response(template_file, t)

mysql命令:

[root@localhost dc]# mysql dc -e 'SELECT * FROM inventory WHERE hosts="localhost"'
+----+-----------+-----------+------+
| id | groups    | hosts     | loc  |
+----+-----------+-----------+------+
|  1 | localhost | localhost |  sf  |
+----+-----------+-----------+------+

3 个回答

0

看看下面的代码,希望能让你更清楚你想要实现的目标。在你的settings.py文件中,确保有一行代码指定了模板的路径,像这样:TEMPLATE_DIRS = ('var/www/dc/templates/')。你需要根据你自己系统的实际路径来修改这个设置。同时,确保在INSTALLED_APPS中添加了'dc'。

settings.py

TEMPLATE_DIRS = ('var/www/dc/templates/')

views.py

from django.shortcuts import render, HttpResponseRedirect, render_to_response
from dc.models import inventory

def gethost(request, hostname):

   try:
       inventory_data = inventory.objets.get(hostname=hostname)
       return render(request,'gethost.html',{inventory:'inventory_data'})

   except inventory.DoesNotExist:

         return HttpResponseRedirect('/myurl/') 
         # this is a dummy url you must set it to a 404 if you want

gethost.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h2>View Hostname: {{inventory.hostname}}</h2>

</body>
</html>

models.py

from django.db import models

class inventory(models.Model):

hostname = models.CharField(max_length=100)

def __unicode__(self):
    return self.hostname
0

你的网址没有传递任何信息,建议使用ORM(对象关系映射)而不是基于SQL的方式。

url(r'^gethost/(?P<hostname>[\w\-]+)/$', 'dc.views.gethost'),
1

感谢大家的及时帮助。

@eddwinpaz,这个问题在视图中解决了。

== views.py:

def gethost(request, hostname, template_file="gethost.html"):
  from django.db import connection, transaction
  cursor = connection.cursor()
  cursor.execute("SELECT * FROM inventory WHERE hosts='%s'" % hostname)
  rows = cursor.fetchall()
  t = Context({'results': rows})
  return render_to_response(template_file, t)

撰写回答