赞
踩
现在很多写bottle微框架的博主都是糊弄事,简单写一个路由入口就不了了事,而谈不到bottle如何解决具体项目,因此想通过一次小的练习来让大家进一步了解bottle微框架的魅力,并可以通过自己的努力写出一个小的项目。
初始创建bottle微框架项目,为了后期方便请创建
apps文件夹
log日志文件夹
static静态文件夹
templates模板文件夹
utils工具箱文件夹
这里将使用官方推荐实用的gevent模块,突破线程池的限制,建议直接复制。
#!/usr/bin/python # -*- coding: UTF-8 -*- from gevent import monkey; monkey.patch_all() from bottle import route, static_file, run, TEMPLATE_PATH import logging import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) TEMPLATE_PATH.append('/'.join((BASE_DIR, 'templates'))) @route('<filename:re:.*\.css|.*\.js|.*\.png|.*\.jpg|.*\.jpeg|.*\.gif|.*\.otf|.*\.eot|.*\.woff|.*\.mp3|.*\.map|.*\.mp4>') def server_static(filename): """定义static下所有的静态资源路径""" return static_file(filename, root='static') # 这里导入你的路由路劲 from apps.view import * log_path = ('/'.join((BASE_DIR, 'log'))) logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', filename="%s/error_log" % log_path, filemode='a') HOST = '0.0.0.0' PORT = sys.argv[1] if len(sys.argv) > 1 else '8080' data = os.popen(f"netstat -ano| findstr {HOST}:{PORT}").read() try: process = data.split("\n")[0].split("LISTENING")[1].replace(" ", "") result = os.popen(f"taskkill /f -pid {process}").read() print(result) except:pass run(server='tornado', host=HOST, port=PORT, reloader=True)
```python from bottle_sqlalchemy import sessionmaker from bottle_sqlalchemy import SQLAlchemyPlugin from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine import bottle import bottle_session import bottle_redis import redis app = bottle.app() def db_config(): DATABASES = { 'ENGINE': 'mysqlconnector', # 默认使用mysqlconnector连接数据库,pip install mysql-connector 'USER': 'root', #数据库软件名 'PASSWORD': '123465', #数据库软件密码 'NAME': 'bottle', #您创建的数据库名 'HOST': '127.0.0.1', # ip地址 } return 'mysql+{}://{}:{}@{}/{}?charset=utf8mb4&autocommit=true'.format(DATABASES['ENGINE'], DATABASES['USER'], DATABASES['PASSWORD'], DATABASES['HOST'], DATABASES['NAME'],) Base = declarative_base() engine = create_engine(db_config(), echo=True, pool_size=100, pool_recycle=3600) Session = sessionmaker(autocommit=False, autoflush=True, bind=engine) db = Session()
If you want to use this model, you can follow these steps in view.py, or you can not allow this model.
''' @route('/') def test(session, rdb): rdb.incr('visitors') visitor_num = rdb.get('visitors') # when cookie_lifetime=10, last_visit_time will be None last_visit_time = session['visit'] session['visit'] = datetime.now().isoformat() # first time when you login this website, you can setting a dict like follwing session['name'] = '我爱你' name = session.get('name') return '<p>{},{},{}</p>'.format(visitor_num, last_visit_time, name) ''' session_plugin = bottle_session.SessionPlugin(cookie_lifetime=10) redis_plugin = bottle_redis.RedisPlugin() connection_pool = redis.ConnectionPool(host='127.0.0.1', port=6379) session_plugin.connection_pool = connection_pool redis_plugin.redisdb = connection_pool app.install(session_plugin) app.install(redis_plugin)
bottle
bottle_sqlalchemy
sqlalchemy
mysqlclient
pymysql
beaker
gevent
tornado
mysql-connector
接下来就开始我们探索bottle为框架的旅行吧
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。