Esempio n. 1
0
def create_app(test_config=None):
    app = Flask(__name__)

    CORS(app)

    if test_config is None:
        app.config.from_pyfile("config.py")
    else:
        app.config.update(test_config)

    database = create_engine(app.config['DB_URL'],
                             encoding='utf-8',
                             max_overflow=0)

    ## Persistenace Layer
    user_dao = UserDao(database)
    tweet_dao = TweetDao(database)

    ## Business Layer
    services = Services
    services.user_service = UserService(user_dao, config)
    services.tweet_service = TweetService(tweet_dao)

    ## Create Endpoints
    create_endpoints(app, services)

    return app
Esempio n. 2
0
def create_app(test_config=None):

    app = Flask(__name__)

    if test_config is None:
        app.config.from_pyfile('config.py')
    else:
        app.config.update(test_config)

    database = create_engine(app.config['DB_URL'],
                             encoding='utf-8',
                             max_overflow=0)

    user_dao = UserDao(database)
    tweet_dao = TweetDao(database)

    s3_client = boto3.client('s3',
                             aws_access_key_id=app.config['S3_ACCESS_KEY'],
                             aws_secret_access_key=app.config['S3_SECRET_KEY'])
    services = Services
    services.user_service = UserService(user_dao, app.config, s3_client)
    services.tweet_service = TweetService(tweet_dao)

    create_endpoints(app, services)

    return app
Esempio n. 3
0
def create_app(test_config = None):
    app = Flask(__name__)

    CORS(app)

    if test_config is None:
        app.config.from_pyfile("config.py")
    else:
        app.config.update(test_config)

    database =create_engine(app.config['DB_URL'], encoding='utf-8', max_overflow =0 )

    ## Persistence layer
    user_dao = UserDao(database)
    tweet_dao = TweetDao(database)

    ## Business layer
    services =Services
    services.user_service = UserService(user_dao, app.config)
    services.tweet_service = TweetService(tweet_dao)

    ## 엔드포인트 생성
    create_endpoints(app, services)

    # persistence, business, presentation layer 모두 연결된 flask application 생성
    return app
Esempio n. 4
0
def create_app(test_config=None):
    app = Flask(__name__)

    CORS(app)

    if test_config is None:
        app.config.from_pyfile("config.py")
    else:
        app.config.update(test_config)

    database = create_engine(app.config['DB_URL'],
                             encoding='utf-8',
                             max_overflow=0)

    # Persistenace Layer
    user_dao = UserDao(database)
    tweet_dao = TweetDao(database)

    # Business Layer
    s3_client = boto3.client("s3",
                             aws_access_key_id=app.config['S3_ACCESS_KEY'],
                             aws_secret_access_key=app.config['S3_SECRET_KEY'])

    services = Services
    services.user_service = UserService(user_dao, app.config, s3_client)
    services.tweet_service = TweetService(tweet_dao)

    # 엔드포인트들을 생성
    create_endpoints(app, services)

    return app
Esempio n. 5
0
File: app.py Progetto: s2zan/miniter
def create_app(test_config=None):
    app = Flask(__name__)

    CORS(app)

    if test_config is None:
        # app.config.from_pyfile("config.py")
        app.config.update({
            'DB': config.db,
            'DB_URL': config.db_url,
            'JWT_SECRET_KEY': config.jwt_secret_key
        })
    else:
        app.config.update(test_config)

    database = create_engine(app.config['DB_URL'],
                             encoding='utf-8',
                             max_overflow=0)

    user_dao = UserDao(database)
    tweet_dao = TweetDao(database)

    services = Services
    services.user_service = UserService(user_dao, app.config)
    services.tweet_service = TweetService(tweet_dao)

    create_endpoints(app, services)

    return app
Esempio n. 6
0
def run():
    # create an interceptor
    interceptors = [AuthenticationInterceptor()]
    # create a grpc server and gives it some threads
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10),
                         interceptors=interceptors)
    # associate my tweet service to serer
    tweet_grpc.add_TweetServicer_to_server(TweetService(), server)
    # add port
    server.add_insecure_port('[::]:50052')
    # start the server
    server.start()

    print(f"Start {TweetService.__name__}...")
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)
Esempio n. 7
0
def create_app(test_config = None):
    #import한 Flask 클래스 객체화시켜서 app에 저
    app = Flask(__name__)
    #CORS 문제 해결 위함
    CORS(app)

    if test_config is None:
        app.config.from_pyfile("config.py")
    else:
        app.config.update(test_config)
    database = create_engine(app.config['DB_URL'], encoding= 'utf-8', max_overflow = 0)

    user_dao = UserDao(database)
    tweet_dao = TweetDao(database)

    services = Services
    services.user_service = UserService(user_dao, app.config)
    services.tweet_service = TweetService(tweet_dao)

    create_endpoints(app, services)

    return app
Esempio n. 8
0
def create_app(test_config=None):
    app = Flask(__name__)
    CORS(app)

    if test_config is None:
        app.config.from_pyfile("config.py")
    else:
        app.config.update(test_config)

    database = create_engine(
        app.config['DB_URL'], encoding='UTF-8', max_overflow=0)

    userDao = UserDao(database)
    tweetDao = TweetDao(database)

    service = Service()
    service.tweet_service = TweetService(tweetDao)
    service.user_service = UserService(userDao, app.config)

    create_endpoints(app, service)

    return app
Esempio n. 9
0
def tweet_service():
    return TweetService(TweetDao(database))
Esempio n. 10
0
def create_app(test_config=None):
    app = Flask(__name__)

    CORS(app)

    if test_config is None:
        app.config.from_pyfile("config.py")
    else:
        app.config.update(test_config)

    database = create_engine(app.config['DB_URL'],
                             encoding='utf-8',
                             max_overflow=0)

    ## Persistenace Layer
    user_dao = UserDao(database)
    tweet_dao = TweetDao(database)

    ## Business Layer
    services = Services
    services.user_service = UserService(user_dao, config)
    services.tweet_service = TweetService(tweet_dao)

    ## 엔드포인트들을 생성
    create_endpoints(app, services)

    return app


# import jwt
# import bcrypt
#
# from flask import Flask, request, jsonify, current_app, Response, g
# from flask.json import JSONEncoder
# from sqlalchemy import create_engine, text
# from datetime import datetime, timedelta
# from functools import wraps
# from flask_cors import CORS
#
#
# ## Default JSON encoder는 set를 JSON으로 변환할 수 없다.
# ## 그럼으로 커스텀 엔코더를 작성해서 set을 list로 변환하여
# ## JSON으로 변환 가능하게 해주어야 한다.
# class CustomJSONEncoder(JSONEncoder):
#     def default(self, obj):
#         if isinstance(obj, set):
#             return list(obj)
#
#         return JSONEncoder.default(self, obj)
#
#
# def get_user(user_id):
#     user = current_app.database.execute(text("""
#         SELECT
#             id,
#             name,
#             email,
#             profile
#         FROM users
#         WHERE id = :user_id
#     """), {
#         'user_id': user_id
#     }).fetchone()
#
#     return {
#         'id': user['id'],
#         'name': user['name'],
#         'email': user['email'],
#         'profile': user['profile']
#     } if user else None
#
#
# def insert_user(user):
#     return current_app.database.execute(text("""
#         INSERT INTO users (
#             name,
#             email,
#             profile,
#             hashed_password
#         ) VALUES (
#             :name,
#             :email,
#             :profile,
#             :password
#         )
#     """), user).lastrowid
#
#
# def insert_tweet(user_tweet):
#     return current_app.database.execute(text("""
#         INSERT INTO tweets (
#             user_id,
#             tweet
#         ) VALUES (
#             :id,
#             :tweet
#         )
#     """), user_tweet).rowcount
#
#
# def insert_follow(user_follow):
#     return current_app.database.execute(text("""
#         INSERT INTO users_follow_list (
#             user_id,
#             follow_user_id
#         ) VALUES (
#             :id,
#             :follow
#         )
#     """), user_follow).rowcount
#
#
# def insert_unfollow(user_unfollow):
#     return current_app.database.execute(text("""
#         DELETE FROM users_follow_list
#         WHERE user_id = :id
#         AND follow_user_id = :unfollow
#     """), user_unfollow).rowcount
#
#
# def get_timeline(user_id):
#     timeline = current_app.database.execute(text("""
#         SELECT
#             t.user_id,
#             t.tweet
#         FROM tweets t
#         LEFT JOIN users_follow_list ufl ON ufl.user_id = :user_id
#         WHERE t.user_id = :user_id
#         OR t.user_id = ufl.follow_user_id
#     """), {
#         'user_id': user_id
#     }).fetchall()
#
#     return [{
#         'user_id': tweet['user_id'],
#         'tweet': tweet['tweet']
#     } for tweet in timeline]
#
#
# def get_user_id_and_password(email):
#     row = current_app.database.execute(text("""
#         SELECT
#             id,
#             hashed_password
#         FROM users
#         WHERE email = :email
#     """), {'email': email}).fetchone()
#
#     return {
#         'id': row['id'],
#         'hashed_password': row['hashed_password']
#     } if row else None
#
#
# #########################################################
# #       Decorators
# #########################################################
# def login_required(f):
#     @wraps(f)
#     def decorated_function(*args, **kwargs):
#         access_token = request.headers.get('Authorization')
#         if access_token is not None:
#             try:
#                 payload = jwt.decode(access_token, current_app.config['JWT_SECRET_KEY'], 'HS256')
#             except jwt.InvalidTokenError:
#                 payload = None
#
#             if payload is None: return Response(status=401)
#
#             user_id = payload['user_id']
#             g.user_id = user_id
#             g.user = get_user(user_id) if user_id else None
#         else:
#             return Response(status=401)
#
#         return f(*args, **kwargs)
#
#     return decorated_function
#
#
# def create_app(test_config=None):
#     app = Flask(__name__)
#
#     CORS(app)
#
#     app.json_encoder = CustomJSONEncoder
#
#     if test_config is None:
#         app.config.from_pyfile("config.py")
#     else:
#         app.config.update(test_config)
#
#     database = create_engine(app.config['DB_URL'], encoding='utf-8', max_overflow=0)
#     app.database = database
#
#     @app.route("/ping", methods=['GET'])
#     def ping():
#         return "pong"
#
#     @app.route("/sign-up", methods=['POST'])
#     def sign_up():
#         new_user = request.json
#         new_user['password'] = bcrypt.hashpw(
#             new_user['password'].encode('UTF-8'),
#             bcrypt.gensalt()
#         )
#
#         new_user_id = insert_user(new_user)
#         new_user = get_user(new_user_id)
#
#         return jsonify(new_user)
#
#     @app.route('/login', methods=['POST'])
#     def login():
#         credential = request.json
#         email = credential['email']
#         password = credential['password']
#         user_credential = get_user_id_and_password(email)
#
#         if user_credential and bcrypt.checkpw(password.encode('UTF-8'),
#                                               user_credential['hashed_password'].encode('UTF-8')):
#             user_id = user_credential['id']
#             payload = {
#                 'user_id': user_id,
#                 'exp': datetime.utcnow() + timedelta(seconds=60 * 60 * 24)
#             }
#             token = jwt.encode(payload, app.config['JWT_SECRET_KEY'], 'HS256')
#
#             return jsonify({
#                 'user_id': user_id,
#                 'access_token': token.decode('UTF-8')
#             })
#         else:
#             return '', 401
#
#     @app.route('/tweet', methods=['POST'])
#     @login_required
#     def tweet():
#         user_tweet = request.json
#         user_tweet['id'] = g.user_id
#         tweet = user_tweet['tweet']
#
#         if len(tweet) > 300:
#             return '300자를 초과했습니다', 400
#
#         insert_tweet(user_tweet)
#
#         return '', 200
#
#     @app.route('/follow', methods=['POST'])
#     @login_required
#     def follow():
#         payload = request.json
#         payload['id'] = g.user_id
#
#         insert_follow(payload)
#
#         return '', 200
#
#     @app.route('/unfollow', methods=['POST'])
#     @login_required
#     def unfollow():
#         payload = request.json
#         payload['id'] = g.user_id
#
#         insert_unfollow(payload)
#
#         return '', 200
#
#     @app.route('/timeline/<int:user_id>', methods=['GET'])
#     def timeline(user_id):
#         return jsonify({
#             'user_id': user_id,
#             'timeline': get_timeline(user_id)
#         })
#
#     @app.route('/timeline', methods=['GET'])
#     @login_required
#     def user_timeline():
#         user_id = g.user_id
#
#         return jsonify({
#             'user_id': user_id,
#             'timeline': get_timeline(user_id)
#         })
#
#     return app
def tweet_service():
    tweetDao = TweetDao(database)
    return TweetService(tweetDao)
Esempio n. 12
0
# Load environment variables
load_dotenv()

# Initialize Twitter API
print("Initializing Twitter API...")
twitter_api = TwitterAPI()

# # Initialize Database
print("Initializing DB...")
db_uri = os.getenv("DB_URI")
model_bases = [JobBase]
session = initialize_db(db_uri, model_bases)

# Initialize Services
print("Initializing Services...")
tweet_service = TweetService(session, twitter_api)
job_service = JobService(session, twitter_api)

if __name__ == "__main__":
    args = get_arguments()
    start_time = datetime.now()

    if args.tweet:
        print("Tweeting...")
        tweet_service.tweet_job()
    elif args.scrap_job:
        print("Scrapping jobs....")
        job_service.scrap_jobs()

    end_time = datetime.now()
    duration = end_time - start_time