首页 > 软件测试

Tomcat, MySQL和Python

Python是一门很好的语言,我一直想学习下,前几个周,在亚马逊网上购买了一本《跟着老齐学Python》,在第一季,我严格按照书上的内容进行了学习,并且做了笔记,分享给了网友。但是觉得学得速度实在太慢,于是我改变了策略,给自己制定一个项目,边做项目边学习。
大家都知道我在维护一个网站:“啄木鸟软件测试咨询网”,都是基于手工的方法维护的,这次我想编写一些代码,采用数据库进行维护。于是我选择了通过HTML页面提交表单,由jsp将表单的内容提交到MySQL数据库中。然后定义显示页面模板,通过Python模板中的标签替换成数据库中的内容。HTML表单的格式为:
paper.html
<form method="POST" action="jsp/paper.jsp">
<p>标题:<br><input type="text" name="title" size="70"></p>
<p>内容:<br><textarea rows="10" name="content" cols="70"></textarea></p>
<p><input type="submit" value="提交" name="B1"></p>
</form>
处理的jsp代码为:
paper.jsp
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page language="java" %>
<%@ page import="com.mysql.jdbc.Driver" %>
<%@ page import="java.sql.*" %>
<%
String title=request.getParameter("title");   
String content=request.getParameter("content"); 

title=new String(title.getBytes("iso-8859-1"),"gb2312");  
content=new String(content.getBytes("iso-8859-1"),"gb2312");

title= title.replaceAll("'", "\'");
content= content.replaceAll("'", "\'");
 
//驱动程序名
String driverName="com.mysql.jdbc.Driver";
//数据库用户名
String userName="root";
//密码
String userPasswd="123456";
//数据库名
String dbName="mypaper";
//表名
String tableName="paper";
String sql="insert into paper(name,content,sig) values('"+title+"','"+content+"',1)" ; 
//联结字符串
String url="jdbc:mysql://localhost/"+dbName+"?user="+userName+"&password="+userPasswd; 
Class.forName(driverName).newInstance(); 
Connection connection=DriverManager.getConnection(url); 
Statement statement=connection.createStatement(); 
int count = statement.executeUpdate(sql);  // 执行插入操作的sql语句,并返回插入数据的个数 
out.print("<br>"); 
out.print("数据库操作成功,恭喜你"); 
statement.close(); 
connection.close();
%>
</body>
其中“<%@ page contentType="text/html; charset=gb2312" %>”与“title=new String(title.getBytes("iso-8859-1"),"gb2312"); content=new String(content.getBytes("iso-8859-1"),"gb2312");”为了防止通过content=new String(content.getBytes("iso-8859-1"),"gb2312");的参数为中文乱码。MySQL的表结构为:
create table paper(
   id INT NOT NULL AUTO_INCREMENT,
   name VARCHAR(200) NOT NULL,
   content VARCHAR(5000) NOT NULL,
   sig int NOT NULL,
   PRIMARY KEY (id)
);
下面我们来谈谈mySQL的设置:
一、采用Windows MySQL
1.下载MYSQL安装包
可以去官网下载ZIP包http://www.mysql.com/downloads/mysql/
我安装的是mysql-5.5.23-winx64
2.解压到本地目录
D:\mysql
3.添加系统环境变量
添加系统环境变量是为了在命令控制窗口里更方便点。
新建:MYSQL_HOME ==> D:\mysql 
追加:PATH==>;%MYSQL_HOME%\bin
4. 修改MySQL5.5的配置文件,把my-small.ini改名为my.ini进行编辑
a)在[mysqld]下追加
-------
basedir = "d:\\mysql"
datadir = "d:\\mysql\\data"
character-set-server = gb2312
-------
b) 在[client]下追加
-------
default-character-set = gb2312
-------
5.启动服务
保存my.ini的配置, 然后打开命令行(开始菜单==>运行==>cmd )
输入: mysqld --console 然后回车将看到如下类似内容:
-------
C:\Windows\system32>mysqld --console
120410 14:25:22 [Note] Plugin 'FEDERATED' is disabled.
120410 14:25:22 InnoDB: The InnoDB memory heap is disabled
120410 14:25:22 InnoDB: Mutexes and rw_locks use Windows interlocked functions
120410 14:25:22 InnoDB: Compressed tables use zlib 1.2.3
120410 14:25:22 InnoDB: Initializing buffer pool, size = 128.0M
120410 14:25:22 InnoDB: Completed initialization of buffer pool
120410 14:25:22 InnoDB: highest supported file format is Barracuda.
120410 14:25:22 InnoDB: Waiting for the background threads to start
120410 14:25:23 InnoDB: 1.1.8 started; log sequence number 1595675
120410 14:25:23 [Note] Event Scheduler: Loaded 0 events
120410 14:25:23 [Note] mysqld: ready for connections.
Version: '5.5.22' socket: '' port: 3306 MySQL Community Server (GPL)
-------
==> 证明mysql服务已启动
6. 设置登陆mysql root帐号的的密码
打开新的命令行,输入 mysql -uroot 回车
-------
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.5.22 MySQL Community Server (GPL)

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners. www.2cto.com 

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
-------
==〉看到上面类似内容说明登陆成功,此时的root帐号是没有密码的
执行命令修改密码:

use mysql; 
update user set password=PASSWORD("这里填写你要设置的密码") where user='root';

执行完成后退出mysql操作,然后关闭mysql服务(ctrl+C 关闭另一个命令窗口),然后重启mysql服务
 
然后使用你的root帐号登录 
mysqladmin -u root password 你的密码
网上是这么写的,但我这样出现了下面的错误
Error: Access denied for user 'root'@'localhost' (using password: YES)
原因是ROOT 的密码没设,或者有错误,网上搜了许多的方法都不行,最后这个成功了,不过必须是主机上执行。
直接运行命令行窗口输入下面的
 
mysqladmin -u root password 你的密码
这样就行了,然后再使用 mysqladmin -u root password 你的密码 就可以正常登录了。

7.安装WINDOWS服务
命令行窗口 CD 进入D:\MySql\bin
执行mysqld.exe --install MySQL5.5 --defaults-file="D:\MySql\my.ini"
net start mysql5.5
到服务器里把 MYSQL5.5改成自动,这样每次开机MYSQL服务就会自动启动了

二,安装XAMPP(我采用的是这种方式)
下载安装以后通过控制面板启动MySQL,在C:\xampp\mysql(XAMPP我是安装在C:\xampp下的)建立文件my.ini,内容如下:
[mysqld]
basedir = "C:\xampp\mysql"
datadir = "C:\xampp\mysql\data"
character-set-server = gb2312
[client]
default-character-set = gb2312
进入C:\xampp\mysql\bin目录下,修改文件my.cnf
[client] 
# password       = your_password 
port            = 3306 
socket          = "C:/xampp/mysql/mysql.sock"
default-character-set = gb2312

# The MySQL server
[mysqld]
port= 3306

character-set-server = gb2312
进入MySQL中键入命令:
Show variables like '%char%';查看字符集是否为gb2312
mysql> Show variables like '%char%';
+--------------------------+--------------------------------+
| Variable_name            | Value                          |
+--------------------------+--------------------------------+
| character_set_client     | gb2312                           |
| character_set_connection | gb2312                           |
| character_set_database   | gb2312                          |
| character_set_filesystem | binary                             |
| character_set_results    | gb2312                           |
| character_set_server     | gb2312                          |
| character_set_system     | utf8                            |
| character_sets_dir       | C:\xampp\mysql\share\charsets\     |
+--------------------------+--------------------------------+
8 rows in set (0.00 sec)
把paper.html与paper.jsp放入对应目录下,运行后,通过命令:
mysql>select * from paper;
来检查数据是否插入导数据库中,并且显示为中文

插入数据库中的工作做完了,然后我们来完成把数据库中的数据通过模板来生成网页文件,为什么要生成HTML格式的网页文件主要是为了能更好地让搜索引擎找到我们。首先我们来定义电脑版本的模板文件:
A1.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>啄木鸟软件测试培训网--软件测试培训-- +++1 </title>
<meta name=Keywords content="软件测试,软件测试培训,第三方软件测试,软件本地化,软件培训,软件测试培训">
<meta name=descripton content=" 好的语言,我一直想学习下,前几个周,在亚马逊网上购买了一本《 ">
<link rel="stylesheet" type="text/css" href="../images/public.css"/>

</head>

<body>
<iframe src="../include/head.htm" width="100%" height="350" scrolling="no" frameborder="0"></iframe>
    <div class="Content">
     <div class="con">
     <div class="path"><a href="../index.html">首页</a>  >  软件测试</div>
            <div class="contact">
             <div class="left">
                
                  <div class="customer_news">
                     <p><b><font size="4"> +++1 </font></b></p>
                        <p>
+++2 </p>


<p><a href="http://www.3testing.com">软件测试</a></p>

<p>  </p>

<p>   </p>
<span style="float:right;">【<a href="mailto:shaozz158@126.com">投稿</a>】</span><span style="float:right;">【<a href="javascript:window.close()" style="color:#13A0FF;">关闭窗口</a>】</span><span style="float:right;">【<a href="javascript:window.print()" style="color:#13A0FF;">打印</a>】</span></p>
                    </div>
                   
                </div>
                <iframe src="../include/right.html" width="240" height="640" scrolling="no" frameborder="0" style="float:right;"></iframe>
            </div>
     </div>
    </div>
<iframe src="../include/button.htm" width="100%" height="120" scrolling="no" frameborder="0"></iframe>
</body>
</html>
其中:
 +++1:用标题来替换;
 +++2:用内容来替换;
 好的语言,我一直想学习下,前几个周,在亚马逊网上购买了一本《:用标题的一部分来替换。
手机版本的模板文件也类似:
A2.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no,minimal-ui" name="viewport"/>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black"/>
<meta content="telephone=no" name="format-detection" />
<!-- UC默认竖屏 -->

<meta name="browsermode" content="application" />
<!-- QQ强制竖屏 -->
<meta name="x5-orientation" content="portrait" />

<meta name="x5-page-mode" content="app" />
<title>+++1</title>
<link href="../css/cate.css" rel="stylesheet" type="text/css" />

</head>

<body>
<div class="head02">
     <div class="left" onClick="history.go(-1);"></div>
        <div class="con">我的文章</div>
        <div class="right" onClick="javascript:window.location.href='../index.html'"></div>
    </div>
    <div class="content">
    
        <div class="con">
         <div class="tit">+++1</div>
            <div class="xx">
      <p>+++2</p>

            </div>
        </div>
    </div>    
    <div class="footer">
        <p>啄木鸟软件测试咨询网 版权所有 @2006-2017</p>
        <p>沪ICP备06048994号</p>
    </div>
    <div class="zd"><a onclick="pageScroll()"><img src="../images/top.png" /></a></div>

<script>
function pageScroll(){
    window.scrollBy(0,-100);
    scrolldelay = setTimeout('pageScroll()',100);
    var sTop=document.documentElement.scrollTop+document.body.scrollTop;
    if(sTop==0) clearTimeout(scrolldelay);
}
</script>
</body>
</html>
然后让我们来看看如何让python文件来完成替换:
paper.py
#!/usr/bin/env python
#coding=utf8

import MySQLdb
import re
import time
import codecs

#把HTML中的特殊字符正则替换成HTML格式,一来防止乱码,二来防止CSS注入
def myrepeat(s):
        s=re.sub("<","<",s)
        s=re.sub(">",">",s)
        s=re.sub("\"",""",s)
        s=re.sub("\r\n","<br>",s)
        s=re.sub(" "," ",s)
        return s
def deal(myfile,sig,title,content):
        f1=codecs.open(myfile,encoding='utf8') #以中文格式打开读文件
        myline=f1.read()
        # 替换模板文件标签
        myline=myline.replace('+++1',title)
        myline=myline.replace('+++2',content)
        myline=myline.replace('好的语言,我一直想学习下,前几个周,在亚马逊网上购买了一本《',content[10:40])
        f1.close()
        f2=codecs.open(sig+time+str(i)+".html","w",encoding='utf8')#以中文格式打开写文件
        f2.write(myline)
        f2.close()
        return f2
if __name__=="__main__":
        #连接数据库
        conn = MySQLdb.connect(host="localhost",user="root",passwd="123456",db="mypaper",charset="gb2312")
        cur = conn.cursor()
        cur.execute("select * from paper where sig=1")
        time=time.strftime('%Y%m%d',time.localtime(time.time()))
        lines =cur.fetchall()
        i=0
        for line in lines:
                title=myrepeat(line[1])
                content=myrepeat(line[2]) 
                deal("A1.html","",title,content)
                deal("A2.html","p",title,content)
#为防止下次在生成,把标签设置为1
                cur.execute("update paper set sig=0 where id="+str(line[0]))
                i+=1
        print "转换成功"
在这里需要指出,由于要连接数据库,引入import MySQLdb,你必须先下载安装MySQL-python-1.2.3.win-amd64-py2.7文件,由于我这里是python2.7版本,所以必须以-py2.7结尾。在安装MySQL-python-1.2.3.win-amd64-py2.7的时候如果发现python2.7没有注册,你必须运行以下文件:
reg.py
#  
# script to register Python 2.0 or later for use with win32all  
# and other extensions that require Python registry settings  
#  
# written by Joakim Loew for Secret Labs AB / PythonWare  
#  
# source:  
# http://www.pythonware.com/products/works/articles/regpy20.htm  
#  
# modified by Valentine Gogichashvili as described in http://www.mail-archive.com/distutils-sig@python.org/msg10512.html  
   
import sys  
   
from _winreg import *  
   
# tweak as necessary  
version = sys.version[:3]  
installpath = sys.prefix  
   
regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)  
installkey = "InstallPath"  
pythonkey = "PythonPath"  
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (  
    installpath, installpath, installpath  
)  
   
def RegisterPy():  
    try:  
        reg = OpenKey(HKEY_CURRENT_USER, regpath)  
    except EnvironmentError as e:  
        try:  
            reg = CreateKey(HKEY_CURRENT_USER, regpath)  
            SetValue(reg, installkey, REG_SZ, installpath)  
            SetValue(reg, pythonkey, REG_SZ, pythonpath)  
            CloseKey(reg)  
        except:  
            print "*** Unable to register!"  
            return  
        print "--- Python", version, "is now registered!"  
        return  
    if (QueryValue(reg, installkey) == installpath and  
        QueryValue(reg, pythonkey) == pythonpath):  
        CloseKey(reg)  
        print "=== Python", version, "is already registered!"  
        return  
    CloseKey(reg)  
    print "*** Unable to register!"  
    print "*** You probably have another Python installation!"  
   
if __name__ == "__main__":  
    RegisterPy()
然后在去安装MySQL-python-1.2.3.win-amd64-py2.7

好了,就到这里了,http://www.3testing.com/test/201701170.html 就是我用这种方法生成的网页

软件测试

  

   

投稿关闭窗口打印