简单的连接MySQL与Python的Bottle框架的方法

yipeiwu_com5年前Python基础

Python关于mySQL的连接插件众多,Bottle下也有人专门开发的插件:bottle-mysql具体使用方法见官方,总共感觉其用法限制太多,其使用起来不方便,最适合的当然是,mySQL官网给Python提供的通用官方驱动,用起来很顺手:mysql-connector  具体操作如下:
 

# -*- coding: utf-8 -*-
#!/usr/bin/python
# filename: login_admin.py
# codedtime: 2014-9-7 11:26:11

import bottle
import mysql.connector  # 导入mysql数据库连接器

def check_userinfo():
  a_list = []  # 创建一个空列表
  username = bottle.request.GET.get('loginname','').strip() # 用户名
  password = bottle.request.GET.get('password','').strip()  # 密码
  if username is not None or password is not None:
    try:
      # 连接数据库 
      conn = mysql.connector.connect(user='root', password='123456', database='myblog')   
      cursor = conn.cursor() # 创建数据游标
      
      # 执行查询
      query = ("SELECT username, password FROM mb_users "
           "WHERE username=%s and password=%s")
      cursor.execute(query, (username, password))

      a_list = cursor.fetchall() # fetchone获取一个元组
      #count = int(cursor.rowcount) # 获取元组个数 
      return a_list

    except mysql.connector.Error as err:
      print("Something went wrong: {}".format(err))
      exit()
      
    finally:
      conn.commit() # 提交修改
      cursor.close() # 关闭数据库
      conn.close()
  else:
    return a_list

def login_admin():
  if bottle.request.GET.get('bs-submit','').strip(): #点击登录按钮
    a_list = check_userinfo()
    if a_list:
      a_name = a_list[0][0] # 获得用户名
      return bottle.template('templates/index_user.tpl', username = a_name)
    else:
      return bottle.template('templates/login_admin.tpl', action='/login_admin', 
              error_info='请输入正确的用户名或密码!')
  else:
    return bottle.template('templates/login_admin.tpl', action='', error_info=' ')

    
以上是MySQL在Botlle中的简单用法,

顺便提一下:安装和管理mySQL,建议安装使用XAMPP,XAMPP集成了Apache, MySQL、PHP、Tomcat等多种工具,一次性解决安装,不用自己繁琐的一个个安装和配置,而且管理也很方便。XAMPP安装的MySQL默认用户是:root  密码为空。

相关文章

python logging模块的使用总结

日志级别 CRITICAL 50 ERROR 40 WARNING 30 INFO 20 DEBUG 10 logging.basicConfig()函数中的具...

Python中str.format()详解

1. str.format 的引入 在 Python 中,我们可以使用 + 来连接字符串,在简单情况下这种方式能够很好的工作。但是当我们需要进行复杂的字符串连接时,如果依然使用 + 来...

Python注释、分支结构、循环结构、伪“选择结构”用法实例分析

Python注释、分支结构、循环结构、伪“选择结构”用法实例分析

本文实例讲述了Python注释、分支结构、循环结构、伪“选择结构”用法。分享给大家供大家参考,具体如下: 注释: python使用#作为行注释符,使用三引号作为多行注释符 分支结构:...

详解Python在使用JSON时需要注意的编码问题

详解Python在使用JSON时需要注意的编码问题

写这篇文章的缘由是我使用 reqeusts 库请求接口的时候, 直接使用请求参数里的 json 字段发送数据, 但是服务器无法识别我发送的数据, 排查了好久才知道 requests 内部...

python接口调用已训练好的caffe模型测试分类方法

python接口调用已训练好的caffe模型测试分类方法

训练好了model后,可以通过python调用caffe的模型,然后进行模型测试的输出。 本次测试主要依靠的模型是在caffe模型里面自带训练好的结构参数:~/caffe/models/...