erdewit / ib_insync

Python sync/async framework for Interactive Brokers API
BSD 2-Clause "Simplified" License
2.75k stars 723 forks source link

Get a runtime error when trying to put this into Flask-restful #18

Closed wangzhe3224 closed 6 years ago

wangzhe3224 commented 6 years ago

I try to make this library a rest wrapper but get a run time error when the code try to connect IB gateway. It is good without rest.

RuntimeError: There is no current event loop in thread 'Thread-1'.

`import asyncio import json import datetime from time import time as timetime

from flask import Flask, request, jsonify from flask_restful import Resource, Api, reqparse, abort from flask.json import JSONEncoder

from ib_insync import *

class datetimeJSONEncoder(JSONEncoder):

def default(self, obj):
    if isinstance(obj, datetime.datetime) | \
            isinstance(obj, datetime.date) | \
            isinstance(obj, datetime.time):

        return int(timetime())

    return JSONEncoder.default(self, obj)

app = Flask(name) api = Api(app)

class IbHistAPI(Resource):

def get(self, ibAssetCodes: str, lookback: int):
    iba = IB()
    iba.connect(port=7496, clientId=666, host='127.0.0.1')

    data = {}

    return jsonify(data)

api.add_resource(IbHistAPI, '/ib/getAssetHistory//')

if name == 'main':

app.run(debug=True)`

Any could help me to figure out what is the reason for this? Thanks

Regards, ZHe

erdewit commented 6 years ago

The Flask framework does not work with asyncio. There are other web frameworks like tornado, aiohttp, sanic or quart that use asyncio and can be used to create REST web services.

Flask can be made to work with asyncio using tornado but this is not optimal.

wangzhe3224 commented 6 years ago

Thanks for reply. Clear now.