signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def generate(self): | payload = {<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>}<EOL>if self.data:<EOL><INDENT>payload['<STR_LIT>'] = self.data<EOL><DEDENT>if self.page:<EOL><INDENT>payload['<STR_LIT>'] = {}<EOL>if self.page.id:<EOL><INDENT>payload['<STR_LIT>']['<STR_LIT:id>'] = self.page.id<EOL><DEDENT>if self.page.is_liked:<EOL><INDENT>payload['<STR_LIT>']['<STR_LIT>'] = self.page.is_liked<EOL><DEDENT>if self.page.is_admin:<EOL><INDENT>payload['<STR_LIT>']['<STR_LIT>'] = self.page.is_admin<EOL><DEDENT><DEDENT>if self.user:<EOL><INDENT>payload['<STR_LIT:user>'] = {}<EOL>if self.user.country:<EOL><INDENT>payload['<STR_LIT:user>']['<STR_LIT>'] = self.user.country<EOL><DEDENT>if self.user.locale:<EOL><INDENT>payload['<STR_LIT:user>']['<STR_LIT>'] = self.user.locale<EOL><DEDENT>if self.user.age:<EOL><INDENT>payload['<STR_LIT:user>']['<STR_LIT>'] = {<EOL>'<STR_LIT>': self.user.age[<NUM_LIT:0>],<EOL>'<STR_LIT>': self.user.age[-<NUM_LIT:1>]<EOL>}<EOL><DEDENT>if self.user.oauth_token:<EOL><INDENT>if self.user.oauth_token.token:<EOL><INDENT>payload['<STR_LIT>'] = self.user.oauth_token.token<EOL><DEDENT>if self.user.oauth_token.expires_at is None:<EOL><INDENT>payload['<STR_LIT>'] = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>payload['<STR_LIT>'] = int(time.mktime(self.user.oauth_token.expires_at.timetuple()))<EOL><DEDENT>if self.user.oauth_token.issued_at:<EOL><INDENT>payload['<STR_LIT>'] = int(time.mktime(self.user.oauth_token.issued_at.timetuple()))<EOL><DEDENT><DEDENT><DEDENT>if self.user.id:<EOL><INDENT>payload['<STR_LIT>'] = self.user.id<EOL><DEDENT>encoded_payload = base64.urlsafe_b64encode(<EOL>json.dumps(payload, separators=('<STR_LIT:U+002C>', '<STR_LIT::>')).encode('<STR_LIT:utf-8>')<EOL>)<EOL>encoded_signature = base64.urlsafe_b64encode(hmac.new(<EOL>self.application_secret_key.encode('<STR_LIT:utf-8>'),<EOL>encoded_payload,<EOL>hashlib.sha256<EOL>).digest())<EOL>return '<STR_LIT>' % {<EOL>'<STR_LIT>': encoded_signature,<EOL>'<STR_LIT>': encoded_payload<EOL>}<EOL> | Generate a signed request from this instance. | f12845:c0:m3 |
def __init__(self, oauth_token=False, url='<STR_LIT>', verify_ssl_certificate=True, appsecret=False, timeout=None, version=None): | self.oauth_token = oauth_token<EOL>self.session = requests.session()<EOL>self.url = url.strip('<STR_LIT:/>')<EOL>self.verify_ssl_certificate = verify_ssl_certificate<EOL>self.appsecret = appsecret<EOL>self.timeout = timeout<EOL>self.version = version<EOL> | Initialize GraphAPI with an OAuth access token.
:param oauth_token: A string describing an OAuth access token.
:param version: A string with version ex. '2.2'. | f12846:c0:m0 |
@classmethod<EOL><INDENT>def for_application(self, id, secret_key, api_version=None):<DEDENT> | from facepy.utils import get_application_access_token<EOL>access_token = get_application_access_token(id, secret_key, api_version=api_version)<EOL>return GraphAPI(access_token, version=api_version)<EOL> | Initialize GraphAPI with an OAuth access token for an application.
:param id: An integer describing a Facebook application.
:param secret_key: A String describing the Facebook application's secret key. | f12846:c0:m1 |
def get(self, path='<STR_LIT>', page=False, retry=<NUM_LIT:3>, **options): | response = self._query(<EOL>method='<STR_LIT:GET>',<EOL>path=path,<EOL>data=options,<EOL>page=page,<EOL>retry=retry<EOL>)<EOL>if response is False:<EOL><INDENT>raise FacebookError('<STR_LIT>' % path)<EOL><DEDENT>return response<EOL> | Get an item from the Graph API.
:param path: A string describing the path to the item.
:param page: A boolean describing whether to return a generator that
iterates over each page of results.
:param retry: An integer describing how many times the request may be retried.
:param options: Graph API parameters such as 'limit', 'offset' or 'since'.
Floating-point numbers will be returned as :class:`decimal.Decimal`
instances.
See `Facebook's Graph API documentation <http://developers.facebook.com/docs/reference/api/>`_
for an exhaustive list of parameters. | f12846:c0:m2 |
def post(self, path='<STR_LIT>', retry=<NUM_LIT:0>, **data): | response = self._query(<EOL>method='<STR_LIT:POST>',<EOL>path=path,<EOL>data=data,<EOL>retry=retry<EOL>)<EOL>if response is False:<EOL><INDENT>raise FacebookError('<STR_LIT>' % path)<EOL><DEDENT>return response<EOL> | Post an item to the Graph API.
:param path: A string describing the path to the item.
:param retry: An integer describing how many times the request may be retried.
:param data: Graph API parameters such as 'message' or 'source'.
See `Facebook's Graph API documentation <http://developers.facebook.com/docs/reference/api/>`_
for an exhaustive list of options. | f12846:c0:m3 |
def delete(self, path, retry=<NUM_LIT:3>, **data): | response = self._query(<EOL>method='<STR_LIT>',<EOL>path=path,<EOL>data=data,<EOL>retry=retry<EOL>)<EOL>if response is False:<EOL><INDENT>raise FacebookError('<STR_LIT>' % path)<EOL><DEDENT>return response<EOL> | Delete an item in the Graph API.
:param path: A string describing the path to the item.
:param retry: An integer describing how many times the request may be retried.
:param data: Graph API parameters such as 'main_page_id' or 'location_page_id'.
See `Facebook's Graph API documentation <http://developers.facebook.com/docs/reference/api/>`_
for an exhaustive list of parameters. | f12846:c0:m4 |
def search(self, term, type='<STR_LIT>', page=False, retry=<NUM_LIT:3>, **options): | if type != '<STR_LIT>':<EOL><INDENT>raise ValueError('<STR_LIT>' % type)<EOL><DEDENT>options = dict({<EOL>'<STR_LIT:q>': term,<EOL>'<STR_LIT:type>': type,<EOL>}, **options)<EOL>response = self._query('<STR_LIT:GET>', '<STR_LIT>', options, page, retry)<EOL>return response<EOL> | Search for an item in the Graph API.
:param term: A string describing the search term.
:param type: A string describing the type of items to search for.
:param page: A boolean describing whether to return a generator that
iterates over each page of results.
:param retry: An integer describing how many times the request may be retried.
:param options: Graph API parameters, such as 'center' and 'distance'.
Supported types are only ``place`` since Graph API 2.0.
See `Facebook's Graph API documentation <http://developers.facebook.com/docs/reference/api/>`_
for an exhaustive list of options. | f12846:c0:m5 |
def batch(self, requests): | for request in requests:<EOL><INDENT>if '<STR_LIT:body>' in request:<EOL><INDENT>request['<STR_LIT:body>'] = urlencode(request['<STR_LIT:body>'])<EOL><DEDENT><DEDENT>def _grouper(complete_list, n=<NUM_LIT:1>):<EOL><INDENT>"""<STR_LIT>"""<EOL>for i in range(<NUM_LIT:0>, len(complete_list), n):<EOL><INDENT>yield complete_list[i:i + n]<EOL><DEDENT><DEDENT>responses = []<EOL>for group in _grouper(requests, <NUM_LIT:50>):<EOL><INDENT>responses += self.post(<EOL>batch=json.dumps(group)<EOL>)<EOL><DEDENT>for response, request in zip(responses, requests):<EOL><INDENT>if not response:<EOL><INDENT>yield None<EOL>continue<EOL><DEDENT>try:<EOL><INDENT>yield self._parse(response['<STR_LIT:body>'])<EOL><DEDENT>except FacepyError as exception:<EOL><INDENT>exception.request = request<EOL>yield exception<EOL><DEDENT><DEDENT> | Make a batch request.
:param requests: A list of dictionaries with keys 'method', 'relative_url' and optionally 'body'.
Yields a list of responses and/or exceptions. | f12846:c0:m6 |
def _query(self, method, path, data=None, page=False, retry=<NUM_LIT:0>): | if(data):<EOL><INDENT>data = dict(<EOL>(k.replace('<STR_LIT>', '<STR_LIT:[>'), v) for k, v in data.items())<EOL>data = dict(<EOL>(k.replace('<STR_LIT>', '<STR_LIT:]>'), v) for k, v in data.items())<EOL>data = dict(<EOL>(k.replace('<STR_LIT>', '<STR_LIT::>'), v) for k, v in data.items())<EOL><DEDENT>data = data or {}<EOL>def load(method, url, data):<EOL><INDENT>for key in data:<EOL><INDENT>value = data[key]<EOL>if isinstance(value, (list, dict, set)):<EOL><INDENT>data[key] = json.dumps(value)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>if method in ['<STR_LIT:GET>', '<STR_LIT>']:<EOL><INDENT>response = self.session.request(<EOL>method, url, params=data, allow_redirects=True,<EOL>verify=self.verify_ssl_certificate, timeout=self.timeout<EOL>)<EOL><DEDENT>if method in ['<STR_LIT:POST>', '<STR_LIT>']:<EOL><INDENT>files = {}<EOL>for key in data:<EOL><INDENT>if hasattr(data[key], '<STR_LIT>'):<EOL><INDENT>files[key] = data[key]<EOL><DEDENT><DEDENT>for key in files:<EOL><INDENT>data.pop(key)<EOL><DEDENT>response = self.session.request(<EOL>method, url, data=data, files=files,<EOL>verify=self.verify_ssl_certificate, timeout=self.timeout<EOL>)<EOL><DEDENT>if <NUM_LIT> <= response.status_code < <NUM_LIT>:<EOL><INDENT>self._parse(response.content)<EOL>raise FacebookError(<EOL>'<STR_LIT>',<EOL>response.status_code<EOL>)<EOL><DEDENT><DEDENT>except requests.RequestException as exception:<EOL><INDENT>raise HTTPError(exception)<EOL><DEDENT>result = self._parse(response.content)<EOL>if isinstance(result, dict):<EOL><INDENT>result['<STR_LIT>'] = response.headers<EOL><DEDENT>try:<EOL><INDENT>next_url = result['<STR_LIT>']['<STR_LIT>']<EOL><DEDENT>except (KeyError, TypeError):<EOL><INDENT>next_url = None<EOL><DEDENT>return result, next_url<EOL><DEDENT>def load_with_retry(method, url, data):<EOL><INDENT>remaining_retries = retry<EOL>while True:<EOL><INDENT>try:<EOL><INDENT>return load(method, url, data)<EOL><DEDENT>except FacepyError as e:<EOL><INDENT>log.warn("<STR_LIT>",<EOL>url,<EOL>e,<EOL>remaining_retries,<EOL>)<EOL>if remaining_retries > <NUM_LIT:0>:<EOL><INDENT>remaining_retries -= <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT><DEDENT>def paginate(method, url, data):<EOL><INDENT>while url:<EOL><INDENT>result, url = load_with_retry(method, url, data)<EOL>for key in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>if key in data:<EOL><INDENT>del data[key]<EOL><DEDENT><DEDENT>yield result<EOL><DEDENT><DEDENT>for key in data:<EOL><INDENT>if isinstance(data[key], (list, set, tuple)) and all([isinstance(item, six.string_types) for item in data[key]]):<EOL><INDENT>data[key] = '<STR_LIT:U+002C>'.join(data[key])<EOL><DEDENT><DEDENT>if not path.startswith('<STR_LIT:/>'):<EOL><INDENT>if six.PY2:<EOL><INDENT>path = '<STR_LIT:/>' + six.text_type(path.decode('<STR_LIT:utf-8>'))<EOL><DEDENT>else:<EOL><INDENT>path = '<STR_LIT:/>' + path<EOL><DEDENT><DEDENT>url = self._get_url(path)<EOL>if self.oauth_token:<EOL><INDENT>data['<STR_LIT>'] = self.oauth_token<EOL><DEDENT>if self.appsecret and self.oauth_token:<EOL><INDENT>data['<STR_LIT>'] = self._generate_appsecret_proof()<EOL><DEDENT>if page:<EOL><INDENT>return paginate(method, url, data)<EOL><DEDENT>else:<EOL><INDENT>return load_with_retry(method, url, data)[<NUM_LIT:0>]<EOL><DEDENT> | Fetch an object from the Graph API and parse the output, returning a tuple where the first item
is the object yielded by the Graph API and the second is the URL for the next page of results, or
``None`` if results have been exhausted.
:param method: A string describing the HTTP method.
:param path: A string describing the object in the Graph API.
:param data: A dictionary of HTTP GET parameters (for GET requests) or POST data (for POST requests).
:param page: A boolean describing whether to return an iterator that iterates over each page of results.
:param retry: An integer describing how many times the request may be retried. | f12846:c0:m7 |
def _parse(self, data): | if type(data) == type(bytes()):<EOL><INDENT>try:<EOL><INDENT>data = data.decode('<STR_LIT:utf-8>')<EOL><DEDENT>except UnicodeDecodeError:<EOL><INDENT>return data<EOL><DEDENT><DEDENT>try:<EOL><INDENT>data = json.loads(data, parse_float=Decimal)<EOL><DEDENT>except ValueError:<EOL><INDENT>return data<EOL><DEDENT>if type(data) is dict:<EOL><INDENT>if '<STR_LIT:error>' in data:<EOL><INDENT>error = data['<STR_LIT:error>']<EOL>if error.get('<STR_LIT:type>') == "<STR_LIT>":<EOL><INDENT>exception = OAuthError<EOL><DEDENT>else:<EOL><INDENT>exception = FacebookError<EOL><DEDENT>raise exception(**self._get_error_params(data))<EOL><DEDENT>if '<STR_LIT>' in data:<EOL><INDENT>raise FacebookError(**self._get_error_params(data))<EOL><DEDENT><DEDENT>return data<EOL> | Parse the response from Facebook's Graph API.
:param data: A string describing the Graph API's response. | f12846:c0:m10 |
def _generate_appsecret_proof(self): | if six.PY2:<EOL><INDENT>key = self.appsecret<EOL>message = self.oauth_token<EOL><DEDENT>else:<EOL><INDENT>key = bytes(self.appsecret, '<STR_LIT:utf-8>')<EOL>message = bytes(self.oauth_token, '<STR_LIT:utf-8>')<EOL><DEDENT>return hmac.new(key, message, hashlib.sha256).hexdigest()<EOL> | Returns a SHA256 of the oauth_token signed by appsecret.
https://developers.facebook.com/docs/graph-api/securing-requests/ | f12846:c0:m11 |
def get_extended_access_token(access_token, application_id, application_secret_key, api_version=None): | graph = GraphAPI(version=api_version)<EOL>response = graph.get(<EOL>path='<STR_LIT>',<EOL>client_id=application_id,<EOL>client_secret=application_secret_key,<EOL>grant_type='<STR_LIT>',<EOL>fb_exchange_token=access_token<EOL>)<EOL>try:<EOL><INDENT>components = parse_qs(response)<EOL><DEDENT>except AttributeError: <EOL><INDENT>return response['<STR_LIT>'], None<EOL><DEDENT>token = components['<STR_LIT>'][<NUM_LIT:0>]<EOL>try:<EOL><INDENT>expires_at = datetime.now() + timedelta(seconds=int(components['<STR_LIT>'][<NUM_LIT:0>]))<EOL><DEDENT>except KeyError: <EOL><INDENT>expires_at = None<EOL><DEDENT>return token, expires_at<EOL> | Get an extended OAuth access token.
:param access_token: A string describing an OAuth access token.
:param application_id: An integer describing the Facebook application's ID.
:param application_secret_key: A string describing the Facebook application's secret key.
Returns a tuple with a string describing the extended access token and a datetime instance
describing when it expires. | f12849:m0 |
def get_application_access_token(application_id, application_secret_key, api_version=None): | graph = GraphAPI(version=api_version)<EOL>response = graph.get(<EOL>path='<STR_LIT>',<EOL>client_id=application_id,<EOL>client_secret=application_secret_key,<EOL>grant_type='<STR_LIT>'<EOL>)<EOL>try:<EOL><INDENT>data = parse_qs(response)<EOL>try:<EOL><INDENT>return data['<STR_LIT>'][<NUM_LIT:0>]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise GraphAPI.FacebookError('<STR_LIT>')<EOL><DEDENT><DEDENT>except AttributeError: <EOL><INDENT>return response['<STR_LIT>'], None<EOL><DEDENT> | Get an OAuth access token for the given application.
:param application_id: An integer describing a Facebook application's ID.
:param application_secret_key: A string describing a Facebook application's secret key. | f12849:m1 |
def generate(self, str=None, fpath=None): | self.prepare_storage()<EOL>self.str = self.load_file(fpath) if fpath else self.sanitize(str)<EOL>self.validate_config()<EOL>self.generate_kgrams()<EOL>self.hash_kgrams()<EOL>self.generate_fingerprints()<EOL>return self.fingerprints<EOL> | generates fingerprints of the input. Either provide `str` to compute fingerprint directly from your string or `fpath` to compute fingerprint from the text of the file. Make sure to have your text decoded in `utf-8` format if you pass the input string.
Args:
str (Optional(str)): string whose fingerprint is to be computed.
fpath (Optional(str)): absolute path of the text file whose fingerprint is to be computed.
Returns:
List(int): fingerprints of the input.
Raises:
FingerprintException: If the input string do not meet the requirements of parameters provided for fingerprinting. | f12860:c1:m10 |
def schedule2calendar(schedule, name='<STR_LIT>', using_todo=True): | <EOL>cal = icalendar.Calendar()<EOL>cal.add('<STR_LIT>', '<STR_LIT>')<EOL>cal.add('<STR_LIT>', name)<EOL>cls = icalendar.Todo if using_todo else icalendar.Event<EOL>for week, start, end, data in schedule:<EOL><INDENT>item = cls(<EOL>SUMMARY='<STR_LIT>'.format(week, data),<EOL>DTSTART=icalendar.vDatetime(start),<EOL>DTEND=icalendar.vDatetime(end),<EOL>DESCRIPTION='<STR_LIT>'.format(start.strftime('<STR_LIT>'), end.strftime('<STR_LIT>'))<EOL>)<EOL>now = datetime.now()<EOL>if using_todo:<EOL><INDENT>if start < now < end:<EOL><INDENT>item.add('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>elif now > end:<EOL><INDENT>item.add('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT><DEDENT>cal.add_component(item)<EOL><DEDENT>return cal<EOL> | 将上课时间表转换为 icalendar
:param schedule: 上课时间表
:param name: 日历名称
:param using_todo: 使用 ``icalendar.Todo`` 而不是 ``icalendar.Event`` 作为活动类
:return: icalendar.Calendar() | f12870:m0 |
def get_point(grade_str): | try:<EOL><INDENT>grade = float(grade_str)<EOL>assert <NUM_LIT:0> <= grade <= <NUM_LIT:100><EOL>if <NUM_LIT> <= grade <= <NUM_LIT:100>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif <NUM_LIT> <= grade < <NUM_LIT>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif <NUM_LIT> <= grade < <NUM_LIT>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif <NUM_LIT> <= grade < <NUM_LIT>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif <NUM_LIT> <= grade < <NUM_LIT>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif <NUM_LIT> <= grade < <NUM_LIT>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif <NUM_LIT> <= grade < <NUM_LIT>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif <NUM_LIT> <= grade < <NUM_LIT>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif <NUM_LIT> <= grade < <NUM_LIT>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif <NUM_LIT:64> <= grade < <NUM_LIT>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif <NUM_LIT> <= grade < <NUM_LIT:64>:<EOL><INDENT>return <NUM_LIT:1.0><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:0.0><EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>if grade_str == '<STR_LIT>':<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif grade_str == '<STR_LIT>':<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif grade_str == '<STR_LIT>':<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif grade_str == '<STR_LIT>':<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif grade_str in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return <NUM_LIT:0.0><EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(grade_str))<EOL><DEDENT><DEDENT> | 根据成绩判断绩点
:param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩
:return: 成绩绩点
:rtype: float | f12873:m0 |
def cal_gpa(grades): | <EOL>courses_sum = len(grades)<EOL>points_sum = <NUM_LIT:0><EOL>credit_sum = <NUM_LIT:0><EOL>gpa_points_sum = <NUM_LIT:0><EOL>for grade in grades:<EOL><INDENT>point = get_point(grade.get('<STR_LIT>') or grade['<STR_LIT>'])<EOL>credit = float(grade['<STR_LIT>'])<EOL>points_sum += point<EOL>credit_sum += credit<EOL>gpa_points_sum += credit * point<EOL><DEDENT>ave_point = points_sum / courses_sum<EOL>gpa = gpa_points_sum / credit_sum<EOL>return round(ave_point, <NUM_LIT:5>), round(gpa, <NUM_LIT:5>)<EOL> | 根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考
:param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组
:return: 包含了课程平均绩点和 gpa 的元组 | f12873:m1 |
def cal_term_code(year, is_first_term=True): | if year <= <NUM_LIT>:<EOL><INDENT>msg = '<STR_LIT>'.format(year)<EOL>raise ValueError(msg)<EOL><DEDENT>term_code = (year - <NUM_LIT>) * <NUM_LIT:2><EOL>if is_first_term:<EOL><INDENT>term_code -= <NUM_LIT:1><EOL><DEDENT>return '<STR_LIT>' % term_code<EOL> | 计算对应的学期代码
:param year: 学年开始年份,例如 "2012-2013学年第二学期" 就是 2012
:param is_first_term: 是否为第一学期
:type is_first_term: bool
:return: 形如 "022" 的学期代码 | f12873:m2 |
def term_str2code(term_str): | result = ENV['<STR_LIT>'].match(term_str).groups()<EOL>year = int(result[<NUM_LIT:0>])<EOL>return cal_term_code(year, result[<NUM_LIT:1>] == '<STR_LIT>')<EOL> | 将学期字符串转换为对应的学期代码串
:param term_str: 形如 "2012-2013学年第二学期" 的学期字符串
:return: 形如 "022" 的学期代码 | f12873:m3 |
def sort_hosts(hosts, method='<STR_LIT:GET>', path='<STR_LIT:/>', timeout=(<NUM_LIT:5>, <NUM_LIT:10>), **kwargs): | ranks = []<EOL>class HostCheckerThread(Thread):<EOL><INDENT>def __init__(self, host):<EOL><INDENT>super(HostCheckerThread, self).__init__()<EOL>self.host = host<EOL><DEDENT>def run(self):<EOL><INDENT>INFINITY = <NUM_LIT><EOL>try:<EOL><INDENT>url = urllib.parse.urljoin(self.host, path)<EOL>res = requests.request(method, url, timeout=timeout, **kwargs)<EOL>res.raise_for_status()<EOL>cost = res.elapsed.total_seconds() * <NUM_LIT:1000><EOL><DEDENT>except Exception as e:<EOL><INDENT>logger.warning('<STR_LIT>', e)<EOL>cost = INFINITY<EOL><DEDENT>ranks.append((cost, self.host))<EOL><DEDENT><DEDENT>threads = [HostCheckerThread(u) for u in hosts]<EOL>for t in threads:<EOL><INDENT>t.start()<EOL><DEDENT>for t in threads:<EOL><INDENT>t.join()<EOL><DEDENT>ranks.sort()<EOL>return ranks<EOL> | 测试各个地址的速度并返回排名, 当出现错误时消耗时间为 INFINITY = 10000000
:param method: 请求方法
:param path: 默认的访问路径
:param hosts: 进行的主机地址列表, 如 `['http://222.195.8.201/']`
:param timeout: 超时时间, 可以是一个浮点数或 形如 ``(连接超时, 读取超时)`` 的元祖
:param kwargs: 其他传递到 ``requests.request`` 的参数
:return: 形如 ``[(访问耗时, 地址)]`` 的排名数据 | f12873:m4 |
def filter_curriculum(curriculum, week, weekday=None): | if weekday:<EOL><INDENT>c = [deepcopy(curriculum[weekday - <NUM_LIT:1>])]<EOL><DEDENT>else:<EOL><INDENT>c = deepcopy(curriculum)<EOL><DEDENT>for d in c:<EOL><INDENT>l = len(d)<EOL>for t_idx in range(l):<EOL><INDENT>t = d[t_idx]<EOL>if t is None:<EOL><INDENT>continue<EOL><DEDENT>t = list(filter(lambda k: week in k['<STR_LIT>'], t)) or None<EOL>if t is not None and len(t) > <NUM_LIT:1>:<EOL><INDENT>logger.warning('<STR_LIT>', week, weekday or c.index(d) + <NUM_LIT:1>, t_idx + <NUM_LIT:1>, t)<EOL><DEDENT>d[t_idx] = t<EOL><DEDENT><DEDENT>return c[<NUM_LIT:0>] if weekday else c<EOL> | 筛选出指定星期[和指定星期几]的课程
:param curriculum: 课程表数据
:param week: 需要筛选的周数, 是一个代表周数的正整数
:param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日
:return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程 | f12873:m5 |
def curriculum2schedule(curriculum, first_day, compress=False, time_table=None): | schedule = []<EOL>time_table = time_table or (<EOL>(timedelta(hours=<NUM_LIT:8>), timedelta(hours=<NUM_LIT:8>, minutes=<NUM_LIT:50>)),<EOL>(timedelta(hours=<NUM_LIT:9>), timedelta(hours=<NUM_LIT:9>, minutes=<NUM_LIT:50>)),<EOL>(timedelta(hours=<NUM_LIT:10>, minutes=<NUM_LIT:10>), timedelta(hours=<NUM_LIT:11>)),<EOL>(timedelta(hours=<NUM_LIT:11>, minutes=<NUM_LIT:10>), timedelta(hours=<NUM_LIT:12>)),<EOL>(timedelta(hours=<NUM_LIT>), timedelta(hours=<NUM_LIT>, minutes=<NUM_LIT:50>)),<EOL>(timedelta(hours=<NUM_LIT:15>), timedelta(hours=<NUM_LIT:15>, minutes=<NUM_LIT:50>)),<EOL>(timedelta(hours=<NUM_LIT:16>), timedelta(hours=<NUM_LIT:16>, minutes=<NUM_LIT:50>)),<EOL>(timedelta(hours=<NUM_LIT>), timedelta(hours=<NUM_LIT>, minutes=<NUM_LIT:50>)),<EOL>(timedelta(hours=<NUM_LIT>), timedelta(hours=<NUM_LIT>, minutes=<NUM_LIT:50>)),<EOL>(timedelta(hours=<NUM_LIT>, minutes=<NUM_LIT:50>), timedelta(hours=<NUM_LIT:20>, minutes=<NUM_LIT>)),<EOL>(timedelta(hours=<NUM_LIT:20>, minutes=<NUM_LIT>), timedelta(hours=<NUM_LIT>, minutes=<NUM_LIT:30>))<EOL>)<EOL>for i, d in enumerate(curriculum):<EOL><INDENT>for j, cs in enumerate(d):<EOL><INDENT>for c in cs or []:<EOL><INDENT>course = '<STR_LIT>'.format(name=c['<STR_LIT>'], place=c['<STR_LIT>'])<EOL>for week in c['<STR_LIT>']:<EOL><INDENT>day = first_day + timedelta(weeks=week - <NUM_LIT:1>, days=i)<EOL>start, end = time_table[j]<EOL>item = (week, day + start, day + end, course)<EOL>schedule.append(item)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>schedule.sort()<EOL>if compress:<EOL><INDENT>new_schedule = [schedule[<NUM_LIT:0>]]<EOL>for i in range(<NUM_LIT:1>, len(schedule)):<EOL><INDENT>sch = schedule[i]<EOL>if new_schedule[-<NUM_LIT:1>][<NUM_LIT:1>].date() == sch[<NUM_LIT:1>].date() and new_schedule[-<NUM_LIT:1>][<NUM_LIT:3>] == sch[<NUM_LIT:3>]:<EOL><INDENT>old_item = new_schedule.pop()<EOL>new_item = (old_item[<NUM_LIT:0>], old_item[<NUM_LIT:1>], sch[<NUM_LIT:2>], old_item[<NUM_LIT:3>])<EOL><DEDENT>else:<EOL><INDENT>new_item = sch<EOL><DEDENT>new_schedule.append(new_item)<EOL><DEDENT>return new_schedule<EOL><DEDENT>return schedule<EOL> | 将课程表转换为上课时间表, 如果 compress=False 结果是未排序的, 否则为压缩并排序后的上课时间表
:param curriculum: 课表
:param first_day: 第一周周一, 如 datetime.datetime(2016, 8, 29)
:param compress: 压缩连续的课时为一个
:param time_table: 每天上课的时间表, 形如 ``((start timedelta, end timedelta), ...)`` 的 11 × 2 的矩阵
:return: [(datetime.datetime, str) ...] | f12873:m6 |
def parse_tr_strs(trs): | tr_strs = []<EOL>for tr in trs:<EOL><INDENT>strs = []<EOL>for td in tr.find_all('<STR_LIT>'):<EOL><INDENT>text = td.get_text(strip=True)<EOL>strs.append(text or None)<EOL><DEDENT>tr_strs.append(strs)<EOL><DEDENT>logger.debug('<STR_LIT>', pformat(tr_strs))<EOL>return tr_strs<EOL> | 将没有值但有必须要的单元格的值设置为 None
将 <tr> 标签数组内的单元格文字解析出来并返回一个二维列表
:param trs: <tr> 标签或标签数组, 为 :class:`bs4.element.Tag` 对象
:return: 二维列表 | f12874:m1 |
def flatten_list(multiply_list): | if isinstance(multiply_list, list):<EOL><INDENT>return [rv for l in multiply_list for rv in flatten_list(l)]<EOL><DEDENT>else:<EOL><INDENT>return [multiply_list]<EOL><DEDENT> | 碾平 list::
>>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
>>> flatten_list(a)
[1, 2, 3, 4, 5, 6, 7, 8]
:param multiply_list: 混淆的多层列表
:return: 单层的 list | f12874:m2 |
def dict_list_2_tuple_set(dict_list_or_tuple_set, reverse=False): | if reverse:<EOL><INDENT>return [dict(l) for l in dict_list_or_tuple_set]<EOL><DEDENT>return {tuple(six.iteritems(d)) for d in dict_list_or_tuple_set}<EOL> | >>> dict_list_2_tuple_set([{'a': 1, 'b': 2}, {'c': 3, 'd': 4}])
{(('c', 3), ('d', 4)), (('a', 1), ('b', 2))}
>>> dict_list_2_tuple_set({(('c', 3), ('d', 4)), (('a', 1), ('b', 2))}, reverse=True)
[{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]
:param dict_list_or_tuple_set: 如果 ``reverse=False`` 为字典列表, 否则为元组集合
:param reverse: 是否反向转换 | f12874:m3 |
def dict_list_2_matrix(dict_list, columns): | k = len(columns)<EOL>n = len(dict_list)<EOL>result = [[None] * k for i in range(n)]<EOL>for i in range(n):<EOL><INDENT>row = dict_list[i]<EOL>for j in range(k):<EOL><INDENT>col = columns[j]<EOL>if col in row:<EOL><INDENT>result[i][j] = row[col]<EOL><DEDENT>else:<EOL><INDENT>result[i][j] = None<EOL><DEDENT><DEDENT><DEDENT>return result<EOL> | >>> dict_list_2_matrix([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], ('a', 'b'))
[[1, 2], [3, 4]]
:param dict_list: 字典列表
:param columns: 字典的键 | f12874:m4 |
def parse_course(course_str): | <EOL>p = re.compile(r'<STR_LIT>')<EOL>courses = p.findall(course_str)<EOL>results = []<EOL>for course in courses:<EOL><INDENT>d = {'<STR_LIT>': course[<NUM_LIT:0>], '<STR_LIT>': course[<NUM_LIT:1>]}<EOL>week_str = course[<NUM_LIT:2>]<EOL>l = week_str.split('<STR_LIT:U+002C>')<EOL>weeks = []<EOL>for v in l:<EOL><INDENT>m = re.match(r'<STR_LIT>', v) or re.match(r'<STR_LIT>', v) or re.match(r'<STR_LIT>', v)<EOL>g = m.groups()<EOL>gl = len(g)<EOL>if gl == <NUM_LIT:1>:<EOL><INDENT>weeks.append(int(g[<NUM_LIT:0>]))<EOL><DEDENT>elif gl == <NUM_LIT:2>:<EOL><INDENT>weeks.extend([i for i in range(int(g[<NUM_LIT:0>]), int(g[<NUM_LIT:1>]) + <NUM_LIT:1>)])<EOL><DEDENT>else:<EOL><INDENT>weeks.extend([i for i in range(int(g[<NUM_LIT:0>]), int(g[<NUM_LIT:1>]) + <NUM_LIT:1>, <NUM_LIT:2>)])<EOL><DEDENT><DEDENT>d['<STR_LIT>'] = weeks<EOL>results.append(d)<EOL><DEDENT>return results<EOL> | 解析课程表里的课程
:param course_str: 形如 `单片机原理及应用[新安学堂434 (9-15周)]/数字图像处理及应用[新安学堂434 (1-7周)]/` 的课程表数据 | f12874:m5 |
def report_response(response,<EOL>request_headers=True, request_body=True,<EOL>response_headers=False, response_body=False,<EOL>redirection=False): | <EOL>url = '<STR_LIT>'.format(<EOL>method=response.request.method, url=response.url,<EOL>status=response.status_code, elapsed=response.elapsed.total_seconds() * <NUM_LIT:1000><EOL>)<EOL>pieces = [url]<EOL>if request_headers:<EOL><INDENT>request_headers = '<STR_LIT>'.format(request_headers=response.request.headers)<EOL>pieces.append(request_headers)<EOL><DEDENT>if request_body:<EOL><INDENT>request_body = '<STR_LIT>'.format(request_body=response.request.body)<EOL>pieces.append(request_body)<EOL><DEDENT>if response_headers:<EOL><INDENT>response_headers = '<STR_LIT>'.format(response_headers=response.headers)<EOL>pieces.append(response_headers)<EOL><DEDENT>if response_body:<EOL><INDENT>response_body = '<STR_LIT>'.format(response_body=response.text)<EOL>pieces.append(response_body)<EOL><DEDENT>reporter = '<STR_LIT:\n>'.join(pieces)<EOL>if redirection and response.history:<EOL><INDENT>for h in response.history[::-<NUM_LIT:1>]:<EOL><INDENT>redirect_reporter = report_response(<EOL>h,<EOL>request_headers, request_body,<EOL>response_headers, response_body,<EOL>redirection=False<EOL>)<EOL>reporter = '<STR_LIT:\n>'.join([redirect_reporter, '<STR_LIT>'.center(<NUM_LIT>, '<STR_LIT:->'), reporter])<EOL><DEDENT><DEDENT>return reporter<EOL> | 生成响应报告
:param response: ``requests.models.Response`` 对象
:param request_headers: 是否加入请求头
:param request_body: 是否加入请求体
:param response_headers: 是否加入响应头
:param response_body: 是否加入响应体
:param redirection: 是否加入重定向响应
:return: str | f12875:m0 |
def get_system_status(self): | return self.query(GetSystemStatus())<EOL> | 获取教务系统当前状态信息, 包括当前学期以及选课计划
@structure {'当前学期': str, '选课计划': [(float, float)], '当前轮数': int or None} | f12877:c1:m1 |
def get_class_students(self, xqdm, kcdm, jxbh): | return self.query(GetClassStudents(xqdm, kcdm, jxbh))<EOL> | 教学班查询, 查询指定教学班的所有学生
@structure {'学期': str, '班级名称': str, '学生': [{'姓名': str, '学号': int}]}
:param xqdm: 学期代码
:param kcdm: 课程代码
:param jxbh: 教学班号 | f12877:c1:m2 |
def get_class_info(self, xqdm, kcdm, jxbh): | return self.query(GetClassInfo(xqdm, kcdm, jxbh))<EOL> | 获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息
@structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str,
'时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str}
:param xqdm: 学期代码
:param kcdm: 课程代码
:param jxbh: 教学班号 | f12877:c1:m3 |
def search_course(self, xqdm, kcdm=None, kcmc=None): | return self.query(SearchCourse(xqdm, kcdm, kcmc))<EOL> | 课程查询
@structure [{'任课教师': str, '课程名称': str, '教学班号': str, '课程代码': str, '班级容量': int}]
:param xqdm: 学期代码
:param kcdm: 课程代码
:param kcmc: 课程名称 | f12877:c1:m4 |
def get_teaching_plan(self, xqdm, kclx='<STR_LIT:b>', zydm='<STR_LIT>'): | return self.query(GetTeachingPlan(xqdm, kclx, zydm))<EOL> | 专业教学计划查询, 可以查询全校公选课, 此时可以不填 `zydm`
@structure [{'开课单位': str, '学时': int, '课程名称': str, '课程代码': str, '学分': float}]
:param xqdm: 学期代码
:param kclx: 课程类型参数,只有两个值 b:专业必修课, x:全校公选课
:param zydm: 专业代码, 可以从 :meth:`models.StudentSession.get_code` 获得 | f12877:c1:m5 |
def get_teacher_info(self, jsh): | return self.query(GetTeacherInfo(jsh))<EOL> | 教师信息查询
@structure {'教研室': str, '教学课程': str, '学历': str, '教龄': str, '教师寄语': str, '简 历': str, '照片': str,
'科研方向': str, '出生': str, '姓名': str, '联系电话': [str], '职称': str, '电子邮件': str, '性别': str, '学位': str,
'院系': str]
:param jsh: 8位教师号, 例如 '05000162' | f12877:c1:m6 |
def get_course_classes(self, kcdm): | return self.query(GetCourseClasses(kcdm))<EOL> | 获取选课系统中课程的可选教学班级(不可选的班级即使人数未满也不能选)
@structure {'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int,
'教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}],
'课程代码': str, '课程名称': str}
:param kcdm: 课程代码 | f12877:c1:m7 |
def get_entire_curriculum(self, xqdm=None): | return self.query(GetEntireCurriculum(xqdm))<EOL> | 获取全校的学期课程表, 当没有提供学期代码时默认返回本学期课程表
@structure {'课表': [[[{'上课周数': [int], '课程名称': str, '课程地点': str}]]], '起始周': int, '结束周': int}
:param xqdm: 学期代码 | f12877:c1:m8 |
def get_code(self): | return self.query(GetCode())<EOL> | 获取当前所有的学期, 学期以及对应的学期代码, 注意如果你只是需要获取某个学期的代码的话请使用 :func:`util.cal_term_code`
@structure {'专业': [{'专业代码': str, '专业名称': str}], '学期': [{'学期代码': str, '学期名称': str}]} | f12877:c2:m1 |
def get_my_info(self): | return self.query(GetMyInfo())<EOL> | 获取个人信息
@structure {'婚姻状况': str, '毕业高中': str, '专业简称': str, '家庭地址': str, '能否选课': str, '政治面貌': str,
'性别': str, '学院简称': str, '外语语种': str, '入学方式': str, '照片': str, '联系电话': str, '姓名': str,
'入学时间': str, '籍贯': str, '民族': str, '学号': int, '家庭电话': str, '生源地': str, '出生日期': str,
'学籍状态': str, '身份证号': str, '考生号': int, '班级简称': str, '注册状态': str} | f12877:c2:m2 |
def get_my_achievements(self): | return self.query(GetMyAchievements())<EOL> | 获取个人成绩
@structure [{'教学班号': str, '课程名称': str, '学期': str, '补考成绩': str, '课程代码': str, '学分': float, '成绩': str}] | f12877:c2:m3 |
def get_my_curriculum(self): | return self.query(GetMyCurriculum())<EOL> | 获取个人课表
@structure {'课表': [[[{'上课周数': [int], '课程名称': str, '课程地点': str}]]], '起始周': int, '结束周': int} | f12877:c2:m4 |
def get_my_fees(self): | return self.query(GetMyFees())<EOL> | 收费查询
@structure [{'教学班号': str, '课程名称': str, '学期': str, '收费(元): float', '课程代码': str, '学分': float}] | f12877:c2:m5 |
def change_password(self, new_password): | if self.session.campus == HF:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if new_password == self.session.password:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>result = self.query(ChangePassword(self.session.password, new_password))<EOL>if result:<EOL><INDENT>self.session.password = new_password<EOL><DEDENT>return result<EOL> | 修改教务密码, **注意** 合肥校区使用信息中心账号登录, 与教务密码不一致, 即使修改了也没有作用, 因此合肥校区帐号调用此接口会直接报错
@structure bool
:param new_password: 新密码 | f12877:c2:m6 |
def set_telephone(self, tel): | return type(tel)(self.query(SetTelephone(tel))) == tel<EOL> | 更新电话
@structure bool
:param tel: 电话号码, 需要满足手机和普通电话的格式, 例如 `18112345678` 或者 '0791-1234567' | f12877:c2:m7 |
def get_optional_courses(self, kclx='<STR_LIT:x>'): | return self.query(GetOptionalCourses(kclx))<EOL> | 获取可选课程, 并不判断是否选满
@structure [{'学分': float, '开课院系': str, '课程代码': str, '课程名称': str, '课程类型': str}]
:param kclx: 课程类型参数,只有三个值,{x:全校公选课, b:全校必修课, jh:本专业计划},默认为'x' | f12877:c2:m8 |
def get_selected_courses(self): | return self.query(GetSelectedCourses())<EOL> | 获取所有已选的课程
@structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}] | f12877:c2:m9 |
def get_unfinished_evaluation(self): | return self.query(GetUnfinishedEvaluation())<EOL> | 获取未完成的课程评价
@structure [{'教学班号': str, '课程名称': str, '课程代码': str}] | f12877:c2:m10 |
def evaluate_course(self, kcdm, jxbh,<EOL>r101=<NUM_LIT:1>, r102=<NUM_LIT:1>, r103=<NUM_LIT:1>, r104=<NUM_LIT:1>, r105=<NUM_LIT:1>, r106=<NUM_LIT:1>, r107=<NUM_LIT:1>, r108=<NUM_LIT:1>, r109=<NUM_LIT:1>,<EOL>r201=<NUM_LIT:3>, r202=<NUM_LIT:3>, advice='<STR_LIT>'): | return self.query(EvaluateCourse(<EOL>kcdm, jxbh,<EOL>r101, r102, r103, r104, r105, r106, r107, r108, r109,<EOL>r201, r202, advice<EOL>))<EOL> | 课程评价, 数值为 1-5, r1 类选项 1 为最好, 5 为最差, r2 类选项程度由深到浅, 3 为最好.
默认都是最好的选项
:param kcdm: 课程代码
:param jxbh: 教学班号
:param r101: 教学态度认真,课前准备充分
:param r102: 教授内容充实,要点重点突出
:param r103: 理论联系实际,反映最新成果
:param r104: 教学方法灵活,师生互动得当
:param r105: 运用现代技术,教学手段多样
:param r106: 注重因材施教,加强能力培养
:param r107: 严格要求管理,关心爱护学生
:param r108: 处处为人师表,注重教书育人
:param r109: 教学综合效果
:param r201: 课程内容
:param r202: 课程负担
:param advice: 其他建议,不能超过120字且不能使用分号,单引号,都好
:return: | f12877:c2:m11 |
def change_course(self, select_courses=None, delete_courses=None): | <EOL>t = self.get_system_status()<EOL>if t['<STR_LIT>'] is None:<EOL><INDENT>raise ValueError('<STR_LIT>', t['<STR_LIT>'])<EOL><DEDENT>if not (select_courses or delete_courses):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>select_courses = select_courses or []<EOL>delete_courses = {l.upper() for l in (delete_courses or [])}<EOL>selected_courses = self.get_selected_courses()<EOL>selected_kcdms = {course['<STR_LIT>'] for course in selected_courses}<EOL>unselected = delete_courses.difference(selected_kcdms)<EOL>if unselected:<EOL><INDENT>msg = '<STR_LIT>'.format(unselected)<EOL>logger.warning(msg)<EOL><DEDENT>kcdms_data = []<EOL>jxbhs_data = []<EOL>for course in selected_courses:<EOL><INDENT>if course['<STR_LIT>'] not in delete_courses:<EOL><INDENT>kcdms_data.append(course['<STR_LIT>'])<EOL>jxbhs_data.append(course['<STR_LIT>'])<EOL><DEDENT><DEDENT>for kv in select_courses:<EOL><INDENT>kcdm = kv['<STR_LIT>'].upper()<EOL>jxbhs = set(kv['<STR_LIT>']) if kv.get('<STR_LIT>') else set()<EOL>teaching_classes = self.get_course_classes(kcdm)<EOL>if not teaching_classes:<EOL><INDENT>logger.warning('<STR_LIT>', kcdm)<EOL>continue<EOL><DEDENT>optional_jxbhs = {c['<STR_LIT>'] for c in teaching_classes['<STR_LIT>']}<EOL>if jxbhs:<EOL><INDENT>wrong_jxbhs = jxbhs.difference(optional_jxbhs)<EOL>if wrong_jxbhs:<EOL><INDENT>msg = '<STR_LIT>'.format(kcdm, teaching_classes['<STR_LIT>'], wrong_jxbhs)<EOL>logger.warning(msg)<EOL><DEDENT>jxbhs = jxbhs.intersection(optional_jxbhs)<EOL><DEDENT>else:<EOL><INDENT>jxbhs = optional_jxbhs<EOL><DEDENT>for jxbh in jxbhs:<EOL><INDENT>kcdms_data.append(kcdm)<EOL>jxbhs_data.append(jxbh)<EOL><DEDENT><DEDENT>return self.query(ChangeCourse(self.session.account, select_courses, delete_courses))<EOL> | 修改个人的课程
@structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}]
:param select_courses: 形如 ``[{'kcdm': '9900039X', 'jxbhs': {'0001', '0002'}}]`` 的课程代码与教学班号列表,
jxbhs 可以为空代表选择所有可选班级
:param delete_courses: 需要删除的课程代码集合, 如 ``{'0200011B'}``
:return: 选课结果, 返回选中的课程教学班列表, 结构与 ``get_selected_courses`` 一致 | f12877:c2:m12 |
def check_courses(self, kcdms): | selected_courses = self.get_selected_courses()<EOL>selected_kcdms = {course['<STR_LIT>'] for course in selected_courses}<EOL>result = [True if kcdm in selected_kcdms else False for kcdm in kcdms]<EOL>return result<EOL> | 检查课程是否被选
@structure [bool]
:param kcdms: 课程代码列表
:return: 与课程代码列表长度一致的布尔值列表, 已为True,未选为False | f12877:c2:m13 |
def get_selectable_courses(self, kcdms=None, pool_size=<NUM_LIT:5>, dump_result=True, filename='<STR_LIT>', encoding='<STR_LIT:utf-8>'): | now = time.time()<EOL>t = self.get_system_status()<EOL>if not (t['<STR_LIT>'][<NUM_LIT:0>][<NUM_LIT:1>] < now < t['<STR_LIT>'][<NUM_LIT:2>][<NUM_LIT:1>]):<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT>def iter_kcdms():<EOL><INDENT>for l in self.get_optional_courses():<EOL><INDENT>yield l['<STR_LIT>']<EOL><DEDENT><DEDENT>kcdms = kcdms or iter_kcdms()<EOL>def target(kcdm):<EOL><INDENT>course_classes = self.get_course_classes(kcdm)<EOL>if not course_classes:<EOL><INDENT>return<EOL><DEDENT>course_classes['<STR_LIT>'] = [c for c in course_classes['<STR_LIT>'] if c['<STR_LIT>'] > c['<STR_LIT>']]<EOL>if len(course_classes['<STR_LIT>']) > <NUM_LIT:0>:<EOL><INDENT>return course_classes<EOL><DEDENT><DEDENT>pool = Pool(pool_size)<EOL>result = list(filter(None, pool.map(target, kcdms)))<EOL>pool.close()<EOL>pool.join()<EOL>if dump_result:<EOL><INDENT>json_str = json.dumps(result, ensure_ascii=False, indent=<NUM_LIT:4>, sort_keys=True)<EOL>with open(filename, '<STR_LIT:wb>') as fp:<EOL><INDENT>fp.write(json_str.encode(encoding))<EOL><DEDENT>logger.info('<STR_LIT>', filename)<EOL><DEDENT>return result<EOL> | 获取所有能够选上的课程的课程班级, 注意这个方法遍历所给出的课程和它们的可选班级, 当选中人数大于等于课程容量时表示不可选.
由于请求非常耗时且一般情况下用不到, 因此默认推荐在第一轮选课结束后到第三轮选课结束之前的时间段使用, 如果你仍然坚持使用, 你将会得到一个警告.
@structure [{'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int,
'教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}],
'课程代码': str, '课程名称': str}]
:param kcdms: 课程代码列表, 默认为所有可选课程的课程代码
:param dump_result: 是否保存结果到本地
:param filename: 保存的文件路径
:param encoding: 文件编码 | f12877:c2:m14 |
def __init__(self, campus): | super(BaseSession, self).__init__()<EOL>self.headers = ENV['<STR_LIT>']<EOL>self.histories = deque(maxlen=ENV['<STR_LIT>'])<EOL>self.campus = campus.upper()<EOL>self.host = ENV[self.campus]<EOL> | 所以接口会话类的基类
:param campus: 校区代码, 请使用 ``value`` 模块中的 ``HF``, ``XC`` 分别来区分合肥校区和宣城校区 | f12880:c0:m0 |
def send(self, request, **kwargs): | response = super(BaseSession, self).send(request, **kwargs)<EOL>if ENV['<STR_LIT>']:<EOL><INDENT>response.raise_for_status()<EOL><DEDENT>parsed = parse.urlparse(response.url)<EOL>if parsed.netloc == parse.urlparse(self.host).netloc:<EOL><INDENT>response.encoding = ENV['<STR_LIT>']<EOL>min_length, max_length, pattern = ENV['<STR_LIT>']<EOL>if min_length <= len(response.content) <= max_length and pattern.search(response.text):<EOL><INDENT>msg = '<STR_LIT>'<EOL>raise IPBanned(msg)<EOL><DEDENT><DEDENT>self.histories.append(response)<EOL>logger.debug(report_response(response, redirection=kwargs.get('<STR_LIT>')))<EOL>return response<EOL> | 所有接口用来发送请求的方法, 只是 :meth:`requests.sessions.Session.send` 的一个钩子方法, 用来处理请求前后的工作 | f12880:c0:m2 |
def __init__(self, account, password, campus): | <EOL>super(StudentSession, self).__init__(campus)<EOL>self.account = account<EOL>self.password = password<EOL>self.name = None<EOL>self.last_request_at = <NUM_LIT:0><EOL> | :param account: 学号
:param password: 密码 | f12880:c2:m0 |
@property<EOL><INDENT>def is_expired(self):<DEDENT> | now = time.time()<EOL>return (now - self.last_request_at) >= <NUM_LIT><EOL> | asp.net 如果程序中没有设置session的过期时间,那么session过期时间就会按照IIS设置的过期时间来执行,
IIS中session默认过期时间为20分钟,网站配置 最长24小时,最小15分钟, 页面级>应用程序级>网站级>服务器级.
.那么当超过 15 分钟未操作会认为会话已过期需要重新登录
:return: 会话是否过期 | f12880:c2:m3 |
def login(self): | <EOL>self.cookies.clear_session_cookies()<EOL>if self.campus == HF:<EOL><INDENT>login_data = {'<STR_LIT>': self.account, '<STR_LIT>': self.password}<EOL>login_url = '<STR_LIT>'<EOL>super(StudentSession, self).request('<STR_LIT>', login_url, data=login_data)<EOL>method = '<STR_LIT>'<EOL>url = '<STR_LIT>'<EOL>data = None<EOL><DEDENT>else:<EOL><INDENT>method = '<STR_LIT>'<EOL>url = '<STR_LIT>'<EOL>data = {"<STR_LIT:user>": self.account, "<STR_LIT:password>": self.password, "<STR_LIT>": '<STR_LIT>'}<EOL><DEDENT>response = super(StudentSession, self).request(method, url, data=data, allow_redirects=False)<EOL>logged_in = response.status_code == <NUM_LIT><EOL>if not logged_in:<EOL><INDENT>msg = '<STR_LIT>'<EOL>raise SystemLoginFailed(msg)<EOL><DEDENT>escaped_name = self.cookies.get('<STR_LIT>')<EOL>if six.PY3:<EOL><INDENT>self.name = parse.unquote(escaped_name, ENV['<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>name = parse.unquote(escaped_name)<EOL>self.name = name.decode(ENV['<STR_LIT>'])<EOL><DEDENT> | 登录账户 | f12880:c2:m4 |
@classmethod<EOL><INDENT>def setUpClass(cls):<DEDENT> | super(ESTestCase, cls).setUpClass()<EOL>if not getattr(settings, '<STR_LIT>', None):<EOL><INDENT>cls.skip_tests = True<EOL>return<EOL><DEDENT>try:<EOL><INDENT>cls.get_es().cluster.health()<EOL><DEDENT>except ConnectionError:<EOL><INDENT>cls.skip_tests = True<EOL>return<EOL><DEDENT>cls._old_es_disabled = settings.ES_DISABLED<EOL>settings.ES_DISABLED = False<EOL>cls._old_es_indexes = settings.ES_INDEXES<EOL>settings.ES_INDEXES = testify(settings.ES_INDEXES)<EOL>for index in settings.ES_INDEXES.values():<EOL><INDENT>cls.get_es().indices.delete(index=index, ignore=<NUM_LIT>)<EOL><DEDENT> | Sets up the environment for ES tests
* pings the ES server---if this fails, it marks all the tests
for skipping
* fixes settings
* deletes the test index if there is one | f12882:c0:m0 |
def setUp(self): | if self.skip_tests:<EOL><INDENT>return skip_this_test()<EOL><DEDENT>super(ESTestCase, self).setUp()<EOL> | Skips the test if this class is skipping tests. | f12882:c0:m1 |
@classmethod<EOL><INDENT>def tearDownClass(cls):<DEDENT> | if not cls.skip_tests:<EOL><INDENT>for index in settings.ES_INDEXES.values():<EOL><INDENT>cls.cleanup_index(index)<EOL><DEDENT>settings.ES_DISABLED = cls._old_es_disabled<EOL>settings.ES_INDEXES = cls._old_es_indexes<EOL><DEDENT>super(ESTestCase, cls).tearDownClass()<EOL> | Tears down environment
* unfixes settings
* deletes the test index | f12882:c0:m2 |
@classmethod<EOL><INDENT>def get_es(cls):<DEDENT> | return get_es()<EOL> | Returns an ES
Override this if you need different settings for your
ES. | f12882:c0:m3 |
@classmethod<EOL><INDENT>def create_index(cls, index, settings=None):<DEDENT> | settings = settings or {}<EOL>cls.get_es().indices.create(index=index, **settings)<EOL> | Creates index with given settings
:arg index: the name of the index to create
:arg settings: dict of settings to set in `create_index` call | f12882:c0:m4 |
@classmethod<EOL><INDENT>def index_data(cls, documents, index, doctype, id_field='<STR_LIT:id>'):<DEDENT> | documents = (dict(d, _id=d[id_field]) for d in documents)<EOL>bulk_index(cls.get_es(), documents, index=index, doc_type=doctype)<EOL>cls.refresh(index)<EOL> | Bulk indexes given data.
This does a refresh after the data is indexed.
:arg documents: list of python dicts each a document to index
:arg index: name of the index
:arg doctype: mapping type name
:arg id_field: the field the document id is stored in in the
document | f12882:c0:m5 |
@classmethod<EOL><INDENT>def refresh(cls, index):<DEDENT> | cls.get_es().indices.refresh(index=index)<EOL>cls.get_es().cluster.health(wait_for_status='<STR_LIT>')<EOL> | Refresh index after indexing.
:arg index: the name of the index to refresh. use ``_all``
to refresh all of them | f12882:c0:m7 |
def get_es(**overrides): | defaults = {<EOL>'<STR_LIT>': settings.ES_URLS,<EOL>'<STR_LIT>': getattr(settings, '<STR_LIT>', <NUM_LIT:5>)<EOL>}<EOL>defaults.update(overrides)<EOL>return base_get_es(**defaults)<EOL> | Return a elasticsearch Elasticsearch object using settings
from ``settings.py``.
:arg overrides: Allows you to override defaults to create the
ElasticSearch object. You can override any of the arguments
isted in :py:func:`elasticutils.get_es`.
For example, if you wanted to create an ElasticSearch with a
longer timeout to a different cluster, you'd do:
>>> from elasticutils.contrib.django import get_es
>>> es = get_es(urls=['http://some_other_cluster:9200'], timeout=30) | f12890:m0 |
def es_required(fun): | @wraps(fun)<EOL>def wrapper(*args, **kw):<EOL><INDENT>if getattr(settings, '<STR_LIT>', False):<EOL><INDENT>log.debug('<STR_LIT>' % fun)<EOL>return<EOL><DEDENT>return fun(*args, es=get_es(), **kw)<EOL><DEDENT>return wrapper<EOL> | Wrap a callable and return None if ES_DISABLED is False.
This also adds an additional `es` argument to the callable
giving you an ElasticSearch instance to use. | f12890:m1 |
def __init__(self, mapping_type): | return super(S, self).__init__(mapping_type)<EOL> | Create and return an S.
:arg mapping_type: class; the mapping type that this S is
based on
.. Note::
The :py:class:`elasticutils.S` doesn't require the
`mapping_type` argument, but the
:py:class:`elasticutils.contrib.django.S` does. | f12890:c1:m0 |
def get_es(self, default_builder=get_es): | return super(S, self).get_es(default_builder=default_builder)<EOL> | Returns the elasticsearch Elasticsearch object to use.
This uses the django get_es builder by default which takes
into account settings in ``settings.py``. | f12890:c1:m1 |
def get_indexes(self, default_indexes=None): | doctype = self.type.get_mapping_type_name()<EOL>indexes = (settings.ES_INDEXES.get(doctype) or<EOL>settings.ES_INDEXES['<STR_LIT:default>'])<EOL>if isinstance(indexes, six.string_types):<EOL><INDENT>indexes = [indexes]<EOL><DEDENT>return super(S, self).get_indexes(default_indexes=indexes)<EOL> | Returns the list of indexes to act on based on ES_INDEXES setting | f12890:c1:m2 |
def get_doctypes(self, default_doctypes=None): | doctypes = self.type.get_mapping_type_name()<EOL>if isinstance(doctypes, six.string_types):<EOL><INDENT>doctypes = [doctypes]<EOL><DEDENT>return super(S, self).get_doctypes(default_doctypes=doctypes)<EOL> | Returns the doctypes (or mapping type names) to use. | f12890:c1:m3 |
def get_object(self): | return self.get_model().objects.get(pk=self._id)<EOL> | Returns the database object for this result
By default, this is::
self.get_model().objects.get(pk=self._id) | f12890:c2:m0 |
@classmethod<EOL><INDENT>def get_model(cls):<DEDENT> | raise NoModelError<EOL> | Return the model related to this DjangoMappingType.
This can be any class that has an instance related to this
DjangoMappingtype by id.
Override this to return a model class.
:returns: model class | f12890:c2:m1 |
@classmethod<EOL><INDENT>def get_index(cls):<DEDENT> | indexes = settings.ES_INDEXES<EOL>index = indexes.get(cls.get_mapping_type_name()) or indexes['<STR_LIT:default>']<EOL>if not (isinstance(index, six.string_types)):<EOL><INDENT>index = index[<NUM_LIT:0>]<EOL><DEDENT>return index<EOL> | Gets the index for this model.
The index for this model is specified in `settings.ES_INDEXES`
which is a dict of mapping type -> index name.
By default, this uses `.get_mapping_type()` to determine the
mapping and returns the value in `settings.ES_INDEXES` for that
or ``settings.ES_INDEXES['default']``.
Override this to compute it differently.
:returns: index name to use | f12890:c2:m2 |
@classmethod<EOL><INDENT>def get_mapping_type_name(cls):<DEDENT> | return cls.get_model()._meta.db_table<EOL> | Returns the name of the mapping.
By default, this is::
cls.get_model()._meta.db_table
Override this if you want to compute the mapping type name
differently.
:returns: mapping type string | f12890:c2:m3 |
@classmethod<EOL><INDENT>def search(cls):<DEDENT> | return S(cls)<EOL> | Returns a typed S for this class.
:returns: an `S` for this DjangoMappingType | f12890:c2:m4 |
@classmethod<EOL><INDENT>def get_es(cls, **overrides):<DEDENT> | return get_es(**overrides)<EOL> | Returns an ElasticSearch object using Django settings
Override this if you need special functionality.
:arg overrides: Allows you to override defaults to create the
ElasticSearch object. You can override any of the arguments
listed in :py:func:`elasticutils.get_es`.
:returns: a elasticsearch `Elasticsearch` instance | f12890:c3:m0 |
@classmethod<EOL><INDENT>def get_indexable(cls):<DEDENT> | model = cls.get_model()<EOL>return model.objects.order_by('<STR_LIT:id>').values_list('<STR_LIT:id>', flat=True)<EOL> | Returns the queryset of ids of all things to be indexed.
Defaults to::
cls.get_model().objects.order_by('id').values_list(
'id', flat=True)
:returns: iterable of ids of objects to be indexed | f12890:c3:m1 |
@task<EOL>def index_objects(mapping_type, ids, chunk_size=<NUM_LIT:100>, es=None, index=None): | if settings.ES_DISABLED:<EOL><INDENT>return<EOL><DEDENT>log.debug('<STR_LIT>'.format(<EOL>ids[<NUM_LIT:0>], ids[-<NUM_LIT:1>], len(ids)))<EOL>model = mapping_type.get_model()<EOL>for id_list in chunked(ids, chunk_size):<EOL><INDENT>documents = []<EOL>for obj in model.objects.filter(id__in=id_list):<EOL><INDENT>try:<EOL><INDENT>documents.append(mapping_type.extract_document(obj.id, obj))<EOL><DEDENT>except Exception as exc:<EOL><INDENT>log.exception('<STR_LIT>'.format(<EOL>obj, repr(exc)))<EOL><DEDENT><DEDENT>if documents:<EOL><INDENT>mapping_type.bulk_index(documents, id_field='<STR_LIT:id>', es=es, index=index)<EOL><DEDENT><DEDENT> | Index documents of a specified mapping type.
This allows for asynchronous indexing.
If a mapping_type extends Indexable, you can add a ``post_save``
hook for the model that it's based on like this::
@receiver(dbsignals.post_save, sender=MyModel)
def update_in_index(sender, instance, **kw):
from elasticutils.contrib.django import tasks
tasks.index_objects.delay(MyMappingType, [instance.id])
:arg mapping_type: the mapping type for these ids
:arg ids: the list of ids of things to index
:arg chunk_size: the size of the chunk for bulk indexing
.. Note::
The default chunk_size is 100. The number of documents you
can bulk index at once depends on the size of the
documents.
:arg es: The `Elasticsearch` to use. If you don't specify an
`Elasticsearch`, it'll use `mapping_type.get_es()`.
:arg index: The name of the index to use. If you don't specify one
it'll use `mapping_type.get_index()`. | f12891:m0 |
@task<EOL>def unindex_objects(mapping_type, ids, es=None, index=None): | if settings.ES_DISABLED:<EOL><INDENT>return<EOL><DEDENT>for id_ in ids:<EOL><INDENT>mapping_type.unindex(id_, es=es, index=index)<EOL><DEDENT> | Remove documents of a specified mapping_type from the index.
This allows for asynchronous deleting.
If a mapping_type extends Indexable, you can add a ``pre_delete``
hook for the model that it's based on like this::
@receiver(dbsignals.pre_delete, sender=MyModel)
def remove_from_index(sender, instance, **kw):
from elasticutils.contrib.django import tasks
tasks.unindex_objects.delay(MyMappingType, [instance.id])
:arg mapping_type: the mapping type for these ids
:arg ids: the list of ids of things to remove
:arg es: The `Elasticsearch` to use. If you don't specify an
`Elasticsearch`, it'll use `mapping_type.get_es()`.
:arg index: The name of the index to use. If you don't specify one
it'll use `mapping_type.get_index()`. | f12891:m1 |
@classmethod<EOL><INDENT>def setup_class(cls):<DEDENT> | <EOL>cls.cleanup_index()<EOL>cls.create_index(mappings=cls.mapping)<EOL>if cls.data:<EOL><INDENT>cls.index_data(cls.data)<EOL>cls.refresh()<EOL><DEDENT> | Sets up the index specified by ``cls.index_name``
This will create the index named ``cls.index_name`` with the
mapping specified in ``cls.mapping`` and indexes any data
specified in ``cls.data``.
If you need something different, then override this. | f12892:c0:m0 |
@classmethod<EOL><INDENT>def teardown_class(cls):<DEDENT> | cls.cleanup_index()<EOL> | Removes the index specified by ``cls.index_name``
This should clean up anything created in ``cls.setup_class()``
and anything created by the tests. | f12892:c0:m1 |
@classmethod<EOL><INDENT>def get_es(cls):<DEDENT> | return get_es(**cls.es_settings)<EOL> | Returns the Elasticsearch object specified by ``cls.es_settings`` | f12892:c0:m3 |
@classmethod<EOL><INDENT>def get_s(cls, mapping_type=None):<DEDENT> | if mapping_type is not None:<EOL><INDENT>s = S(mapping_type)<EOL><DEDENT>else:<EOL><INDENT>s = S()<EOL><DEDENT>return (s.es(**cls.es_settings)<EOL>.indexes(cls.index_name)<EOL>.doctypes(cls.mapping_type_name))<EOL> | Returns an S for the settings on this class
Uses ``cls.es_settings`` to configure the Elasticsearch
object. Uses ``cls.index_name`` for the index and
``cls.mapping_type_name`` for the MappingType to search.
:arg mapping_type: The MappingType class to use to create the S | f12892:c0:m4 |
@classmethod<EOL><INDENT>def create_index(cls, **kwargs):<DEDENT> | body = kwargs if kwargs else {}<EOL>cls.get_es().indices.create(index=cls.index_name, body=body)<EOL> | Creates an index with specified settings
Uses ``cls.index_name`` as the index to create.
:arg kwargs: Any additional args to put in the body like
"settings", "mappings", etc. | f12892:c0:m5 |
@classmethod<EOL><INDENT>def index_data(cls, documents, id_field='<STR_LIT:id>'):<DEDENT> | documents = (dict(d, _id=d[id_field]) for d in documents)<EOL>bulk_index(cls.get_es(), documents, index=cls.index_name,<EOL>doc_type=cls.mapping_type_name)<EOL>cls.refresh()<EOL> | Indexes specified data
Uses ``cls.index_name`` as the index to index into. Uses
``cls.mapping_type_name`` as the doctype to index these
documents as.
:arg documents: List of documents as Python dicts
:arg id_field: The field of the document that represents the id | f12892:c0:m6 |
@classmethod<EOL><INDENT>def cleanup_index(cls):<DEDENT> | cls.get_es().indices.delete(index=cls.index_name, ignore=<NUM_LIT>)<EOL> | Cleans up the index
This deletes the index named by ``cls.index_name``. | f12892:c0:m7 |
@classmethod<EOL><INDENT>def refresh(cls):<DEDENT> | cls.get_es().indices.refresh(index=cls.index_name)<EOL>cls.get_es().cluster.health(wait_for_status='<STR_LIT>')<EOL> | Refresh index after indexing
This refreshes the index specified by ``cls.index_name``. | f12892:c0:m8 |
def eqish_(item1, item2): | def _eqish(part1, part2):<EOL><INDENT>if type(part1) != type(part2) or bool(part1) != bool(part2):<EOL><INDENT>return False<EOL><DEDENT>if isinstance(part1, (tuple, list)):<EOL><INDENT>part2_left = list(part2)<EOL>for mem1 in part1:<EOL><INDENT>for i, mem2 in enumerate(part2_left):<EOL><INDENT>if _eqish(mem1, mem2):<EOL><INDENT>del part2_left[i]<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL><DEDENT>elif isinstance(part1, dict):<EOL><INDENT>if sorted(part1.keys()) != sorted(part2.keys()):<EOL><INDENT>return False<EOL><DEDENT>for mem in part1.keys():<EOL><INDENT>if not _eqish(part1[mem], part2[mem]):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return part1 == part2<EOL><DEDENT><DEDENT>if not _eqish(item1, item2):<EOL><INDENT>raise AssertionError('<STR_LIT>'.format(item1, item2))<EOL><DEDENT> | Compare two trees ignoring order of things in lists
Note: This is really goofy, but works for our specific purposes. If you
have other needs, you'll likely need to find a new solution here. | f12894:m0 |
def require_version(minimum_version): | def decorated(test):<EOL><INDENT>"""<STR_LIT>"""<EOL>@wraps(test)<EOL>def test_with_version(self):<EOL><INDENT>"<STR_LIT>"<EOL>actual_version = self.get_es().info()['<STR_LIT:version>']['<STR_LIT>']<EOL>if LooseVersion(actual_version) >= LooseVersion(minimum_version):<EOL><INDENT>test(self)<EOL><DEDENT>else:<EOL><INDENT>raise SkipTest<EOL><DEDENT><DEDENT>return test_with_version<EOL><DEDENT>return decorated<EOL> | Skip the test if the Elasticsearch version is less than specified.
:arg minimum_version: string; the minimum Elasticsearch version required | f12896:m1 |
def get_es(urls=None, timeout=DEFAULT_TIMEOUT, force_new=False, **settings): | <EOL>urls = urls or DEFAULT_URLS<EOL>if '<STR_LIT>' in settings:<EOL><INDENT>raise DeprecationWarning('<STR_LIT>')<EOL><DEDENT>if not force_new:<EOL><INDENT>key = _build_key(urls, timeout, **settings)<EOL>if key in _cached_elasticsearch:<EOL><INDENT>return _cached_elasticsearch[key]<EOL><DEDENT><DEDENT>es = Elasticsearch(urls, timeout=timeout, **settings)<EOL>if not force_new:<EOL><INDENT>_cached_elasticsearch[key] = es<EOL><DEDENT>return es<EOL> | Create an elasticsearch `Elasticsearch` object and return it.
This will aggressively re-use `Elasticsearch` objects with the
following rules:
1. if you pass the same argument values to `get_es()`, then it
will return the same `Elasticsearch` object
2. if you pass different argument values to `get_es()`, then it
will return different `Elasticsearch` object
3. it caches each `Elasticsearch` object that gets created
4. if you pass in `force_new=True`, then you are guaranteed to get
a fresh `Elasticsearch` object AND that object will not be
cached
:arg urls: list of uris; Elasticsearch hosts to connect to,
defaults to ``['http://localhost:9200']``
:arg timeout: int; the timeout in seconds, defaults to 5
:arg force_new: Forces get_es() to generate a new Elasticsearch
object rather than pulling it from cache.
:arg settings: other settings to pass into Elasticsearch
constructor; See
`<http://elasticsearch-py.readthedocs.org/>`_ for more details.
Examples::
# Returns cached Elasticsearch object
es = get_es()
# Returns a new Elasticsearch object
es = get_es(force_new=True)
es = get_es(urls=['localhost'])
es = get_es(urls=['localhost:9200'], timeout=10,
max_retries=3) | f12902:m1 |
def split_field_action(s): | if '<STR_LIT>' in s:<EOL><INDENT>return s.rsplit('<STR_LIT>', <NUM_LIT:1>)<EOL><DEDENT>return s, None<EOL> | Takes a string and splits it into field and action
Example::
>>> split_field_action('foo__bar')
'foo', 'bar'
>>> split_field_action('foo')
'foo', None | f12902:m2 |
def _facet_counts(items): | facets = {}<EOL>for name, data in items:<EOL><INDENT>facets[name] = FacetResult(name, data)<EOL><DEDENT>return facets<EOL> | Returns facet counts as dict.
Given the `items()` on the raw dictionary from Elasticsearch this processes
it and returns the counts keyed on the facet name provided in the original
query. | f12902:m4 |
def _boosted_value(name, action, key, value, boost): | if boost is not None:<EOL><INDENT>value_key = '<STR_LIT>' if action in MATCH_ACTIONS else '<STR_LIT:value>'<EOL>return {name: {'<STR_LIT>': boost, value_key: value}}<EOL><DEDENT>return {name: value}<EOL> | Boost a value if we should in _process_queries | f12902:m5 |
def _convert_results_to_dict(r): | if '<STR_LIT>' in r:<EOL><INDENT>return r['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in r:<EOL><INDENT>return r['<STR_LIT>']<EOL><DEDENT>return {'<STR_LIT:id>': r['<STR_LIT>']}<EOL> | Takes a results from Elasticsearch and returns fields. | f12902:m6 |
def decorate_with_metadata(obj, result): | <EOL>obj.es_meta = Metadata(<EOL>id=result.get('<STR_LIT>', <NUM_LIT:0>),<EOL>source=result.get('<STR_LIT>', {}),<EOL>score=result.get('<STR_LIT>', None),<EOL>type=result.get('<STR_LIT>', None),<EOL>explanation=result.get('<STR_LIT>', {}),<EOL>highlight=result.get('<STR_LIT>', {})<EOL>)<EOL>obj._id = result.get('<STR_LIT>', <NUM_LIT:0>)<EOL>return obj<EOL> | Return obj decorated with es_meta object | f12902:m7 |
def __init__(self, **filters): | filters = filters.items()<EOL>if six.PY3:<EOL><INDENT>filters = list(filters)<EOL><DEDENT>if len(filters) > <NUM_LIT:1>:<EOL><INDENT>self.filters = [{'<STR_LIT>': filters}]<EOL><DEDENT>else:<EOL><INDENT>self.filters = filters<EOL><DEDENT> | Creates an F | f12902:c6:m0 |
def _combine(self, other, conn='<STR_LIT>'): | f = F()<EOL>self_filters = copy.deepcopy(self.filters)<EOL>other_filters = copy.deepcopy(other.filters)<EOL>if not self.filters:<EOL><INDENT>f.filters = other_filters<EOL><DEDENT>elif not other.filters:<EOL><INDENT>f.filters = self_filters<EOL><DEDENT>elif conn in self.filters[<NUM_LIT:0>]:<EOL><INDENT>f.filters = self_filters<EOL>f.filters[<NUM_LIT:0>][conn].extend(other_filters)<EOL><DEDENT>elif conn in other.filters[<NUM_LIT:0>]:<EOL><INDENT>f.filters = other_filters<EOL>f.filters[<NUM_LIT:0>][conn].extend(self_filters)<EOL><DEDENT>else:<EOL><INDENT>f.filters = [{conn: self_filters + other_filters}]<EOL><DEDENT>return f<EOL> | OR and AND will create a new F, with the filters from both F
objects combined with the connector `conn`. | f12902:c6:m2 |
def __init__(self, **queries): | self.should_q = []<EOL>self.must_q = []<EOL>self.must_not_q = []<EOL>should_flag = queries.pop('<STR_LIT>', False)<EOL>must_flag = queries.pop('<STR_LIT>', False)<EOL>must_not_flag = queries.pop('<STR_LIT>', False)<EOL>if should_flag + must_flag + must_not_flag > <NUM_LIT:1>:<EOL><INDENT>raise InvalidFlagsError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if should_flag:<EOL><INDENT>self.should_q.extend(queries.items())<EOL><DEDENT>elif must_not_flag:<EOL><INDENT>self.must_not_q.extend(queries.items())<EOL><DEDENT>else:<EOL><INDENT>self.must_q.extend(queries.items())<EOL><DEDENT> | Creates a Q | f12902:c7:m0 |
def to_python(self, obj): | if isinstance(obj, string_types):<EOL><INDENT>if len(obj) == <NUM_LIT>:<EOL><INDENT>try:<EOL><INDENT>return datetime.strptime(obj, '<STR_LIT>')<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>elif len(obj) == <NUM_LIT>:<EOL><INDENT>try:<EOL><INDENT>return datetime.strptime(obj, '<STR_LIT>')<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>elif len(obj) == <NUM_LIT:10>:<EOL><INDENT>try:<EOL><INDENT>return datetime.strptime(obj, '<STR_LIT>')<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(obj, dict):<EOL><INDENT>for key, val in obj.items():<EOL><INDENT>obj[key] = self.to_python(val)<EOL><DEDENT><DEDENT>elif isinstance(obj, list):<EOL><INDENT>return [self.to_python(item) for item in obj]<EOL><DEDENT>return obj<EOL> | Converts strings in a data structure to Python types
It converts datetime-ish things to Python datetimes.
Override if you want something different.
:arg obj: Python datastructure
:returns: Python datastructure with strings converted to
Python types
.. Note::
This does the conversion in-place! | f12902:c8:m0 |
def __init__(self, type_=None): | self.type = type_<EOL>self.steps = []<EOL>self.start = <NUM_LIT:0><EOL>self.stop = None<EOL>self.as_list = self.as_dict = False<EOL>self.field_boosts = {}<EOL>self._results_cache = None<EOL> | Create and return an S.
:arg type_: class; the MappingType for this S | f12902:c9:m0 |
def es(self, **settings): | return self._clone(next_step=('<STR_LIT>', settings))<EOL> | Return a new S with specified Elasticsearch settings.
This allows you to configure the Elasticsearch object that gets
used to execute the search.
:arg settings: the settings you'd use to build the
Elasticsearch---same as what you'd pass to
:py:func:`get_es`. | f12902:c9:m3 |
def indexes(self, *indexes): | return self._clone(next_step=('<STR_LIT>', indexes))<EOL> | Return a new S instance that will search specified indexes. | f12902:c9:m4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.