Source

py4u-opensource / application.py

Full commit
# -*- coding: utf-8 *-*
from __future__ import with_statement
import gevent
from gevent import monkey
from uuid import uuid4
monkey.patch_all()
from flask import Flask,request,render_template,template_rendered,session,g,redirect,url_for,Response,make_response,send_file,abort
import sqlite3
from mysignal import defer_process
#from serverpush import sphapp,message_collection, Message
from news import User, Post, Comment,Activity
from functools import wraps
from server_session import SqliteSessionInterface
from configure import configure,Configure,Message
from pybook import pybookapp,cache
import datetime
from usercontroller import userapp
import base64
from blinker import signal
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
#some setting
app = Flask(__name__)
app.secret_key = '\x1e*\xa7\xe0\xab\x10\xab\xfcxU|4\xect\xbe\xb3\x8d?B\x99e\xd1\xf0\xe5'
app.register_blueprint(userapp, url_prefix='/useraction')
app.register_blueprint(pybookapp, url_prefix='/pybook')
#app.register_blueprint(sphapp, url_prefix='/serverpush')
#app.register_blueprint(adminapp, url_prefix='/admin')
#mail = Mail(app)

DATABASE = 'db'
SESSION_PATH = './session'
app.session_interface = SqliteSessionInterface(SESSION_PATH)


# set up mobile version
_render_template = render_template
def _my_render_template(*args, **kwargs):
    if request.user_agent.platform == 'iphone' or\
            request.user_agent.platform == 'android' or\
            request.user_agent.string.find("iPad") != -1 :
        args = ('mobile/' + args[0],) + args[1:]
    return _render_template(*args, **kwargs)
render_template = _my_render_template

#set up different language
#http://werkzeug.pocoo.org/docs/utils/#module-werkzeug.useragents



#connect db

def connect_db():
    """Returns a new connection to the database."""
    return sqlite3.connect(DATABASE,detect_types=sqlite3.PARSE_DECLTYPES)

@app.before_request
def before_request():
    """Make sure we are connected to the database each request."""
    if "message" not in session:
        session['message'] = Message("Welcome to PY4U")

    g.db = connect_db()
    # enable foreign key support
    g.db.cursor().execute("PRAGMA foreign_keys = ON")
    g.db.row_factory = sqlite3.Row



@app.teardown_request
def teardown_request(exception):
    #print "finish connection"
    """Closes the database again at the end of the request."""
    if hasattr(g, 'db'):
        g.db.close()
    gevent.joinall(defer_process)

@template_rendered.connect_via(app)
def when_template_rendered(sender, template, context, **extra):
    if(session['message'].content != ""):
        session['message'] = Message("")


@app.context_processor
def inject_configure():
    return dict(configure.__class__.__dict__)
@app.context_processor
def inject_user():
    user=session.get('user',None)
    activities = None
    if(user is not None):
        activities = Activity.get_activities_byuserid(user.id)
    return dict(user = user, activities = activities)
#url process and method
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/hot')
def hotposts():
    page = request.args.get('page',1)
    posts = Post.get_hot_posts(offset = int(page)-1)
    posts.sort(key=lambda tpost:tpost.score, reverse=True)
    return render_template('news.html',posts = posts, nextpage = int(page)+1,currenturl = request.url,news_type='news_hot')

@app.route('/deadpool')
def deadpool():
    page = request.args.get('page',1)
    posts = Post.get_deadpool_posts(offset = int(page)-1)
    posts.sort(key=lambda tpost:tpost.score, reverse=True)
    return render_template('news.html',posts = posts, nextpage = int(page)+1,currenturl = request.url,news_type='news_deadpool')

@app.route('/latest')
def latest():
    page = request.args.get('page',1)
    posts = Post.get_posts_by_postdate(offset = int(page)-1)
    return render_template('news.html', posts = posts, nextpage = int(page)+1,currenturl = request.url,news_type='news_last')

@app.route('/rules')
def rules():
    return render_template('rules.html')
@app.route('/connactus')
def connactus():
    return render_template('connactus.html')

@app.route('/showpost')
def showpost():
    id = request.args['id']
    post = Post.get_post_byid(id)
    post.init_post_poster()
    comments = Comment.get_comments_by_postid(id)
    return render_template('showpost.html', post = post,comments = comments)



@app.route('/login',methods=['GET','POST'])
def login():
    if(request.method =='GET'):
        return render_template('login.html')
    if(request.method == 'POST'):
        email = request.form['email']
        nickname = None
        password = request.form['password']
        user = User(email,nickname,password)
        if(user.is_valid()):
            session['user'] = user
            session['message'] = Message('Login Success')
            return redirect(request.form['to_url'])
        else:
            session['message'] = Message('The email or password is wrong!', 'alert-error')
            return redirect('/login')
        #return render_template('login.html', message="The email or password is wrong!", to_url = request.form['to_url'])

@app.route('/signup',methods=['GET','POST'])
def signup():
    if(request.method =='GET'):
        return render_template('signup.html')
    if(request.method == 'POST'):
        email = request.form['email']
        nickname = request.form['nickname']
        password = request.form['password']
        user = User(email,nickname,password)
        user.save()
        session['user'] = user
        return redirect(url_for('index'))

@app.route('/logout')
def logout():
    if('user' in session):
        session.pop('user')
        session['message'] = Message('Logout Success')
    return render_template('index.html')

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


''' http://flask.pocoo.org/snippets/33/'''
@app.template_filter()
def timesince(dt, default="just now"):
    """
    Returns string representing "time since" e.g.
    3 days ago, 5 hours ago etc.
    """

    now = datetime.datetime.now()#utcnow
    diff = now - dt

    periods = (
        (diff.days / 365, "year", "years"),
        (diff.days / 30, "month", "months"),
        (diff.days / 7, "week", "weeks"),
        (diff.days, "day", "days"),
        (diff.seconds / 3600, "hour", "hours"),
        (diff.seconds / 60, "minute", "minutes"),
        (diff.seconds, "second", "seconds"),
    )

    for period, singular, plural in periods:

        if period:
            return "%d %s ago" % (period, singular if period == 1 else plural)

    return default

'''test'''







if __name__ == '__main__':
    app.debug = True
    app.run(port = 5555)
    import werkzeug.serving
    @werkzeug.serving.run_with_reloader
    def run_gevent_server():
        global app
        from werkzeug.debug import DebuggedApplication
        app.debug = True
        #app = DebuggedApplication(app, True)
        http_server = WSGIServer(('',5555), app, handler_class=WebSocketHandler)
        http_server.serve_forever()

    #run_gevent_server()