Exemple #1
0
def addHeaders(headers, request, response):
    HEADS = [
        'COUNT-SOURCES', 'COUNT-ATOMS', 'COUNT-MOLECULES', 'COUNT-SPECIES',
        'COUNT-STATES', 'COUNT-COLLISIONS', 'COUNT-RADIATIVE',
        'COUNT-NONRADIATIVE', 'TRUNCATED', 'APPROX-SIZE', 'REQUEST-TOKEN'
    ]

    headers = CaselessDict(headers)

    headlist_asString = ''
    for h in HEADS:
        if h in headers:
            response['VAMDC-' + h] = '%s' % headers[h]
            headlist_asString += 'VAMDC-' + h + ', '

    response['Access-Control-Allow-Origin'] = '*'
    response['Access-Control-Expose-Headers'] = headlist_asString[:-2]

    lastmod = headers.get('LAST-MODIFIED')
    if not lastmod and hasattr(settings, 'LAST_MODIFIED'):
        lastmod = settings.LAST_MODIFIED

    if isinstance(lastmod, datetime.date):
        response['Last-Modified'] = getFormatLastModified(lastmod)
    elif isinstance(lastmod, str):
        response['Last-Modified'] = lastmod
    else:
        pass

    return response
Exemple #2
0
    def test_request_headers(self):
        headers = {'User-Agent': 'me', 'X-HeyBoy': 'HeyGirl'}
        resp = self.session.get('http://myapp.local/headers', headers=headers)
        resp.raise_for_status()

        # Turn this into a case-insensitive dictionary to make it easier to
        # compare.
        from requests.utils import CaseInsensitiveDict
        resp_headers = CaseInsensitiveDict(resp.json()['headers'])

        for h_key, h_value in headers.items():
            assert resp_headers.get(h_key) == h_value
Exemple #3
0
def response_callback_factory(status=200, headers=None, body=None, json=None):
    if headers is None:
        headers = CaseInsensitiveDict()
    else:
        headers = CaseInsensitiveDict(headers)
    if json is not None:
        assert body is None
        body = json_dumps(json).encode('utf-8')
        if 'Content-Type' not in headers:
            headers['Content-Type'] = 'application/json'

    def response_callback(request):
        return status, headers, body

    return response_callback
Exemple #4
0
 def _initial_headers(self) -> CaseInsensitiveDict:
     """
     Returns:
       A dictionary with additional headers.
     """
     return CaseInsensitiveDict({
         'User-Agent': self._user_agent,
         'X-Snake-Client': self._user_agent,
         'Accept': 'application/json',
     })
def BibTeX2XML(bibtexstring, key=None):
    """
    Derives an XSAMS source element from the given BibTeX and returns the XML text.
    The ID of the Source is set in the form B(node)-(key) where (node) is replaced
    by the ID string for this node and (key) is replaced by the unique key for this
    Source. If the key argument is given, this value is used for the key; otherwise,
    a key is generated from the BibTeX content.
    """
    e = getEntryFromString(bibtexstring)
    if key:
        xml = u'<Source sourceID="B%s-%s">\n<Authors>\n' % (NODEID, key)
    else:
        xml = u'<Source sourceID="B%s-%s">\n<Authors>\n' % (NODEID, e.key)
    for a in e.persons['author']:
        name = a.first() + a.middle() + a.last() + a.lineage()
        name = [n.strip().strip('{}') for n in name]
        name = ' '.join(name)
        xml += '<Author><Name>%s</Name></Author>' % name
    xml += '\n</Authors>'

    category = TYPE2CATEGORY.get(e.type)

    f = CaselessDict(e.fields)
    url = f.get('bdsk-url-1')
    title = f.get('title', "").strip().strip('{}')
    sourcename = f.get('journal', 'unknown')
    doi = f.get('doi', "")
    year = f.get('year', "")
    volume = f.get('volume', "")
    pages = f.get('pages', "")
    p1, p2 = '', ''
    pages = re.findall(r'[0-9][0-9]*', pages)
    if pages:
        p1 = pages[0]
        if len(pages) > 1:
            p2 = pages[-1]

    xml += """<Title>%s</Title>
<Category>%s</Category>
<Year>%s</Year>
<SourceName>%s</SourceName>
<Volume>%s</Volume>
<PageBegin>%s</PageBegin>
<PageEnd>%s</PageEnd>
<UniformResourceIdentifier>%s</UniformResourceIdentifier>
<DigitalObjectIdentifier>%s</DigitalObjectIdentifier>
""" % (title, category, year or 2222, sourcename, volume, p1, p2, url, doi)

    xml += '<BibTeX>%s</BibTeX></Source>' % quoteattr(bibtexstring)[1:-1]

    return xml
Exemple #6
0
def addHeaders(headers,request,response):
    HEADS=['COUNT-SOURCES',
           'COUNT-ATOMS',
           'COUNT-MOLECULES',
           'COUNT-SPECIES',
           'COUNT-STATES',
           'COUNT-COLLISIONS',
           'COUNT-RADIATIVE',
           'COUNT-NONRADIATIVE',
           'TRUNCATED',
           'APPROX-SIZE',
           'REQUEST-TOKEN']

    headers = CaselessDict(headers)

    headlist_asString=''
    for h in HEADS:
        if h in headers:
            response['VAMDC-'+h] = '%s'%headers[h]
            headlist_asString += 'VAMDC-'+h+', '

    response['Access-Control-Allow-Origin'] = '*'
    response['Access-Control-Expose-Headers'] = headlist_asString[:-2]

    lastmod = headers.get('LAST-MODIFIED')
    if not lastmod and hasattr(settings,'LAST_MODIFIED'):
        lastmod=settings.LAST_MODIFIED

    if isinstance(lastmod,datetime.date):
        response['Last-Modified'] = getFormatLastModified(lastmod)
    elif isinstance(lastmod,str):
        response['Last-Modified'] = lastmod
    else:
        pass

    return response
Exemple #7
0
class OrderSide:
    BUY = 'BUY'
    SELL = 'SELL'

    _all = {BUY, SELL}
    _reverse_side_map = CaseInsensitiveDict(BUY=SELL, SELL=BUY)

    @classmethod
    def validate(cls, side: str) -> str:
        side = side.upper()
        assert side in cls._all, f'{side} not in {cls._all}'
        return side

    @classmethod
    def get_reverse_side(cls, side: str) -> str:
        assert side in cls._reverse_side_map
        return cls._reverse_side_map[side]
Exemple #8
0
 def __initial_headers(self):
     return CaseInsensitiveDict({
         'User-Agent': self._user_agent,
         'X-Snake-Client': self._user_agent,
         'Accept': 'application/json',
     })
Exemple #9
0
ASSET_URL = 'https://hunshcn.github.io/gh-proxy'  # 主页

app = Flask(__name__)
CHUNK_SIZE = 1024 * 10
index_html = requests.get(ASSET_URL, timeout=10).text
icon_r = requests.get(ASSET_URL + '/favicon.ico', timeout=10).content
exp1 = re.compile(
    r'^(?:https?://)?github\.com/.+?/.+?/(?:releases|archive)/.*$')
exp2 = re.compile(r'^(?:https?://)?github\.com/.+?/.+?/(?:blob)/.*$')
exp3 = re.compile(r'^(?:https?://)?github\.com/.+?/.+?/(?:info|git-).*$')
exp4 = re.compile(
    r'^(?:https?://)?raw\.githubusercontent\.com/.+?/.+?/.+?/.+$')
exp5 = re.compile(
    r'^(?:https?://)?gist\.(?:githubusercontent|github)\.com/.+?/.+?/.+$')

requests.sessions.default_headers = lambda: CaseInsensitiveDict()


@app.route('/')
def index():
    if 'q' in request.args:
        return redirect('/' + request.args.get('q'))
    return index_html


@app.route('/favicon.ico')
def icon():
    return Response(icon_r, content_type='image/vnd.microsoft.icon')


def iter_content(self, chunk_size=1, decode_unicode=False):
Exemple #10
0
                            description=challenge['description'],
                            files=list(
                                map(self.__get_file_url,
                                    challenge.get('files', []))))


def get_credentials(username=None, password=None):
    username = username or os.environ.get('CTF_USERNAME',
                                          input('User/Email: '))
    password = password or os.environ.get('CTF_PASSWORD',
                                          getpass('Password: ', stream=False))

    return username, password


CTFs = CaseInsensitiveDict(data={"CTFd": CTFd})


def main(args=None):
    if args is None:
        args = sys.argv[1:]

    parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument("-v",
                        "--version",
                        action="version",
                        version="%(prog)s {ver}".format(ver=__version__))

    parser.add_argument("url",
                        help="ctf url (for example: https://demo.ctfd.io/)")
    parser.add_argument("-c",