2019-04-10 20:41:53 Python

Python

Copy Copied! Full
from flask import Flask, redirect, url_for, session, request, render_template from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from werkzeug.utils import secure_filename from flask_login import UserMixin, LoginManager, login_user, logout_user, current_user from datetime import datetime #from requests_oauthlib import OAuth1Service from rauth import OAuth1Service from http.server import HTTPServer, SimpleHTTPRequestHandler import random, ssl, string, config #SSL取得のためのサーバー # def run(host, port, ctx, handler): # server = HTTPServer((host, port), handler) # server.socket = ctx.wrap_socket(server.socket) # print('Sever Starts -%s:%s' %(host,port)) # try: # server.server_forever() # except KeyboardInterrupt: # pass # server.server_close() # print('Server Stops - %s:%s' % (host, port)) app = Flask(__name__) #セッションに必要な秘密鍵 app.secret_key = 'wj9jr2jg@249j0J4h20JaV91A03f4j2' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://localhost/flasknote" db = SQLAlchemy(app) login_manager = LoginManager(app) login_manager.login_view = 'index' migrate = Migrate(app, db) CONSUMER_KEY = config.ConsumerKey_2 CONSUMER_SECRET = config.ConsumerSecretKey_2 ACCESS_TOKEN = config.AccessToken_2 ACCESS_SECRET = config.AccessSecretToken_2 service = OAuth1Service( name='twitter', consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, request_token_url='https://api.twitter.com/oauth/request_token', access_token_url='https://api.twitter.com/oauth/access_token', authorize_url='https://api.twitter.com/oauth/authorize', base_url='http://api.twitter.com/1.1/' ) class user2(UserMixin, db.Model): #userテーブルクラス __tablename__ = 'user2' #カラム定義 id = db.Column(db.String(10), primary_key=True) username = db.Column(db.String(64), index=True) description = db.Column(db.String(1024), index=True) user_image_url = db.Column(db.String(1024), index=True) date_published = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) twitter_id = db.Column(db.String(64), nullable=False, unique=True) def __repr__(self): return '<user2 %r>' % self.username # def init_db(app): # db.init_app(app) # Migrate(app, db) # @app.route('/') # def index(): # users = user2.query.all() # return render_template('index4.html', users=users) @app.route('/') def index(): return render_template('index.html') @app.route('/logout') def logout(): logout_user() return redirect(url_for('index')) @app.route('/oauth/twitter') def oauth_authorize(): if not current_user.is_anonymous: return redirect(url_for('index')) else: request_token = service.get_request_token( params={'oauth_callback': url_for('oauth_callback', provider='twitter', _external=True)}) session['request_token'] = request_token return redirect(service.get_authorize_url(request_token[0])) @app.route('/oauth/twitter/callback') def oauth_callback(): request_token = session.pop('request_token') oauth_session = service.get_auth_session( request_token[0], request_token[1], data={'oauth_verifier':request.args['oauth_verifier']} ) profile = oauth_session.get('account/verify_credentials.json').json() print('ユーザー情報') print(profile) twitter_id = str(profile.get('id')) username = str(profile.get('name')) description = str(profile.get('description')) profile_image_url = str(profile.get('profile_image_url')) user = db.session.query(user2).filter(user2.twitter_id == twitter_id).first() if user: user.twitter_id = twitter_id user.username = username else: randomId = ''.join(random.choices(string.ascii_letters + string.digits, k=10)) user = user2(id=randomId, twitter_id = twitter_id, username = username, user_image_url = profile_image_url) db.session.add(user) db.session.commit() # このユーザー情報を元にセッションを生成 login_user(user, True) return redirect(url_for('index')) @login_manager.user_loader def load_user(id): return user2.query.get(str(id)) @app.route('/form') def form(): return render_template('form4.html') @app.route('/home') def home(): return render_template('home.html') @app.route('/register', methods=['POST']) def register(): if request.form['username'] and request.form['description'] and request.files['image']: f = request.files['image'] filepath = 'static/' + secure_filename(f.filename) f.save(filepath) filepath = '/' + filepath randomId = ''.join(random.choices(string.ascii_letters + string.digits, k=10)) #あたらしいuserをinsert newUser2 = user2(id=randomId, username=request.form['username'], description=request.form['description'], user_image_url=filepath) db.session.add(newUser2) db.session.commit() return render_template('result.html', username=request.form['username'], description=request.form['description']) else: return render_template('error.html') @app.cli.command('initdb') def initdb_command(): db.create_all() if __name__ == '__main__': # host = 'localhost' # port = 5000 # ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) # ctx.load_cert_chain('server.crt', keyfile='server.key') # ctx.options |= ssl.OP_NO_RLSv1 | ssl.OP_NO_TLSv1_1 # handler = SimpleHTTPRequestHandler # run(host, port, ctx, handler) app.run(debug=True)