py4u-opensource /

Full commit
# -*- coding: utf-8 *-*
from __future__ import with_statement
import gevent
from gevent import monkey
from uuid import uuid4
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)

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

#connect db

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

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

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

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

def inject_configure():
    return dict(configure.__class__.__dict__)
def inject_user():
    activities = None
    if(user is not None):
        activities = Activity.get_activities_byuserid(
    return dict(user = user, activities = activities)
#url process and method
def index():
    return render_template('index.html')

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')

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')

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')

def rules():
    return render_template('rules.html')
def connactus():
    return render_template('connactus.html')

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

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)
            session['user'] = user
            session['message'] = Message('Login Success')
            return redirect(request.form['to_url'])
            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'])

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)
        session['user'] = user
        return redirect(url_for('index'))

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

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

def timesince(dt, default="just now"):
    Returns string representing "time since" e.g.
    3 days ago, 5 hours ago etc.

    now =
    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


if __name__ == '__main__':
    app.debug = True = 5555)
    import werkzeug.serving
    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)