/
flask_solrpy.py
72 lines (58 loc) · 2.19 KB
/
flask_solrpy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'''
Created on Sep 4, 2012
@author: jluker
'''
import logging
from solr import SolrConnection
from flask import g
name = __name__
logger = logging.getLogger(__name__)
class SolrConfigurationError(Exception):
pass
class SolrConnectionError(Exception):
pass
def _create_solr_connection(app):
app.config.setdefault('SOLR_URL', 'http://localhost:8983/solr')
app.config.setdefault('SOLR_PERSISTENT', True)
app.config.setdefault('SOLR_TIMEOUT', 30)
app.config.setdefault('SOLR_POST_HEADERS', {})
app.config.setdefault('SOLR_MAX_RETRIES', 0)
xtra_kwargs = {}
if app.config.has_key('SOLR_SSL_CRED'):
try:
xtra_kwargs['ssl_key'] = app.config['SOLR_SSL_CRED'][0]
xtra_kwargs['ssl_cert'] = app.config['SOLR_SSL_CRED'][1]
except Exception, e:
raise SolrConfigurationError("Bad SOLR_SSL_CRED value: %s" % (str(e)))
if app.config.has_key('SOLR_HTTP_BASIC_AUTH'):
try:
xtra_kwargs['http_user'] = app.config['SOLR_HTTP_BASIC_AUTH'][0]
xtra_kwargs['http_pass'] = app.config['SOLR_HTTP_BASIC_AUTH'][1]
except Exception, e:
raise SolrConfigurationError("Bad SOLR_HTTP_BASIC_AUTH value: %s" % (str(e)))
solr = SolrConnection(
app.config['SOLR_URL'],
persistent=app.config['SOLR_PERSISTENT'],
timeout=app.config['SOLR_TIMEOUT'],
post_headers=app.config['SOLR_POST_HEADERS'],
max_retries=app.config['SOLR_MAX_RETRIES'],
**xtra_kwargs
)
if (app.config.has_key('SOLR_ARG_SEPARATOR')):
solr.select.arg_separator = app.config['SOLR_ARG_SEPARATOR']
return solr
class FlaskSolrpy(object):
"""
Connection to a solr instance using SOLR_URL parameter defined
in Flask configuration
"""
def __init__(self, app=None):
if app is not None:
self.init_app(app)
else:
self.solr = None
def init_app(self, app):
self.solr = _create_solr_connection(app)
app.before_request(self.request_start)
def request_start(self):
g.solr = self.solr