[Python 2.6] BaseHTTPRequestHandler Dynamic response
Bonjour,
je souhaite renvoyer des informations à mon client en fonction de sa requête un peu comme le fonctionnement du site suivant.
http://blog.arnaud-k.fr/2010/09/14/t...erche-en-ajax/
Avec la librairie BaseHTTPRequestHandler j'ai trouvé comment répondre en html ou en effectuant une redirection d'url mais pas réussi en renvoyant uniquement une information.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| <?php
//connexion à la base de données
define('DB_NAME', 'nom_de_la_base');
define('DB_USER', 'nom_utilisateur');
define('DB_PASSWORD', 'mot_de_passe');
define('DB_HOST', 'localhost');
$link = mysql_connect( DB_HOST , DB_USER , DB_PASSWORD );
mysql_select_db( DB_NAME , $link );
//recherche des résultats dans la base de données
$result = mysql_query( 'SELECT post_title , post_date , guid
FROM wp_posts
WHERE post_status = \'publish\'
AND post_title LIKE \'' . safe( $_GET['q'] ) . '%\'
LIMIT 0,20' );
// affichage d'un message "pas de résultats"
if( mysql_num_rows( $result ) == 0 )
{
?>
<h3 style="text-align:center; margin:10px 0;">Pas de résultats pour cette recherche</h3>
<?php
}
else
{
// parcours et affichage des résultats
while( $post = mysql_fetch_object( $result ))
{
?>
<div class="article-result">
<h3><a href="<?php echo $post->guid; ?>">< ?php echo utf8_encode( $post->post_title ); ?></a></h3>
<p class="date"><?php echo $post->post_date; ?></p>
<p class="url"><?php echo $post->guid; ?></p>
</div>
<?php
}
}
/*****
fonctions
*****/
function safe($var)
{
$var = mysql_real_escape_string($var);
$var = addcslashes($var, '%_');
$var = trim($var);
$var = htmlspecialchars($var);
return $var;
}
?> |
Le code php suivant permet de renvoyer des informations, savez vous comment puis je renvoyer l'information en python (avec uniquement les librairies de bases de python 2.6)
Je me suis penché sur :
Code:
return self.response.out.write(form["quest"].value)
Mais je rencontre l'erreur suivante.
Code:
AttributeError: myHandler instance has no attribute 'response'
Code actuel qui n'est qu'une suite de test uniquement...
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| #!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep, path
import cgi
PORT_NUMBER = 36654
#This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
print "do_GET"
print self.path
if self.path=="/":
self.path="/index_example3.html"
try:
#Check the file extension required and
#set the right mime type
sendReply = False
if self.path.endswith(".html"):
mimetype='text/html'
sendReply = True
if self.path.endswith(".jpg"):
mimetype='image/jpg'
sendReply = True
if self.path.endswith(".gif"):
mimetype='image/gif'
sendReply = True
if self.path.endswith(".js"):
mimetype='application/javascript'
sendReply = True
if self.path.endswith(".css"):
mimetype='text/css'
sendReply = True
if sendReply == True:
#Open the static file requested and send it
f = open(curdir + sep + self.path)
self.send_response(200)
self.send_header('Content-type',mimetype)
self.end_headers()
self.wfile.write(f.read())
print "Chargement 1"
f.close()
return
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
#Handler for the POST requests
def do_POST(self):
if self.path=="/send":
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
print "Your name is: %s" % form["your_name"].value
self.path="/index_example5.html"
self.do_GET()
return
if self.path == "/send2":
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
print "Your name is: %s" % form["your_name"].value
self.path="/index.html"
self.do_GET()
return
if self.path.startswith('/search'):
print 'first test'
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
print 'your request : {0}'.format(form["quest"].value)
return self.response.out.write(form["quest"].value)
try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
#Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close() |
Merci d'avance.
Cordialement Quentin.