'Fetch Results for a Twitter Search Query'

@staticmethod
def twitter_search(search_id):

    try:
        import TwitterSearch
    except ImportError:
        error = 'Unresolved    dependency:    TwitterSearch    required    for    fetching    results    from    twitter    keyword    queries'
        current.log.error('s3msg', error)
        current.session.error = error
        redirect(URL(f='index'))
    db = current.db
    s3db = current.s3db
    table = s3db.msg_twitter_channel
    settings = db((table.id > 0)).select(table.consumer_key, table.consumer_secret, table.access_token, table.access_token_secret, limitby=(0, 1)).first()
    if (not settings):
        error = 'Twitter    Search    requires    an    account    configuring'
        current.log.error('s3msg', error)
        current.session.error = error
        redirect(URL(f='twitter_channel'))
    qtable = s3db.msg_twitter_search
    rtable = db.msg_twitter_result
    search_query = db((qtable.id == search_id)).select(qtable.id, qtable.keywords, qtable.lang, qtable.count, qtable.include_entities, limitby=(0, 1)).first()
    tso = TwitterSearch.TwitterSearchOrder()
    tso.setKeywords(search_query.keywords.split('    '))
    tso.setLanguage(search_query.lang)
    tso.setCount(int(search_query.count))
    tso.setIncludeEntities(search_query.include_entities)
    try:
        ts = TwitterSearch.TwitterSearch(consumer_key=settings.consumer_key, consumer_secret=settings.consumer_secret, access_token=settings.access_token, access_token_secret=settings.access_token_secret)
    except TwitterSearch.TwitterSearchException as e:
        return str(e)
    from dateutil import parser
    date_parse = parser.parse
    gtable = db.gis_location
    rtable.location_id.requires = None
    update_super = s3db.update_super
    for tweet in ts.searchTweetsIterable(tso):
        user = tweet['user']['screen_name']
        body = tweet['text']
        tweet_id = tweet['id_str']
        lang = tweet['lang']
        created_at = date_parse(tweet['created_at'])
        lat = None
        lon = None
        if tweet['coordinates']:
            lat = tweet['coordinates']['coordinates'][1]
            lon = tweet['coordinates']['coordinates'][0]
            location_id = gtable.insert(lat=lat, lon=lon)
        else:
            location_id = None
        _id = rtable.insert(from_address=user, search_id=search_id, body=body, tweet_id=tweet_id, lang=lang, date=created_at, location_id=location_id)
        update_super(rtable, dict(id=_id))
    db((qtable.id == search_id)).update(is_searched=True)
    return 'OK'
