Saravanan666/pypi-org huggingface dataset:
Package: httpretty
HTTPretty 1.1.4HTTP Client mocking tool for Python created byGabriel Falcão. It provides a full fake TCP socket module. Inspired byFakeWebGithub RepositoryDocumentationPyPI PackagePython Support:3.63.73.83.9InstallpipinstallhttprettyCommon Use CasesTest-driven development of API integrationsFake responses of external APIsRecord and playback HTTP requestsSimple Exampleimportsureimporthttprettyimportrequests@httpretty.activate(verbose=True,allow_net_connect=False)deftest_httpbin():httpretty.register_uri(httpretty.GET,"https://httpbin.org/ip",body='{"origin": "127.0.0.1"}')response=requests.get('https://httpbin.org/ip')response.json().should.equal({'origin':'127.0.0.1'})httpretty.latest_requests().should.have.length_of(1)httpretty.last_request().should.equal(httpretty.latest_requests()[0])httpretty.last_request().body.should.equal('{"origin": "127.0.0.1"}')checking multiple responses@httpretty.activate(verbose=True,allow_net_connect=False)deftest_post_bodies():url='http://httpbin.org/post'httpretty.register_uri(httpretty.POST,url,status=200)httpretty.register_uri(httpretty.POST,url,status=400)requests.post(url,data={'foo':'bar'})requests.post(url,data={'zoo':'zoo'})assert'foo=bar'inhttpretty.latest_requests()[0].bodyassert'zoo=bar'inhttpretty.latest_requests()[1].bodyLicense<HTTPretty - HTTP client mock for Python>
Copyright (C) <2011-2021> Gabriel Falcão <gabriel@nacaolivre.org>

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.Main contributorsHTTPretty has receivedmany contributionsbut some folks made remarkable contributions and deserve extra credit:Andrew Gross ~>@andrewgrossHugh Saunders ~>@hughsaundersJames Rowe ~>@JNRoweMatt Luongo ~>@mhluongoSteve Pulec ~>@spulecMiro Hrončok ~>@hroncokMario Jonke ~>@mariojonke
Package: http-router
http-router– A simple router for HTTP applicationsThe library is not a HTTP framework. It’s an utilite to build the frameworks.
The main goal of the library to bind targets to http routes and match them.ContentsRequirementsInstallationUsageBug trackerContributingLicenseRequirementspython 3.8, 3.9, 3.10, 3.11, 3.12, pypy3Installationhttp-routershould be installed using pip:pip install http-routerUsageCreate a router:fromhttp_routerimportRouter# Initialize the routerrouter=Router(trim_last_slash=True)Define routes:@router.route('/simple')defsimple():return'result from the fn'Call the router with HTTP path and optionally method to get a match result.match=router('/simple',method='GET')assertmatch,'HTTP path is ok'assertmatch.targetissimpleThe router supports regex objects too:importre@router.route(re.compile(r'/regexp/\w{3}-\d{2}/?'))defregex():return'result from the fn'But the lib has a simplier interface for the dynamic routes:@router.route('/users/{username}')defusers():return'result from the fn'By default this will capture characters up to the end of the path or the next/.Optionally, you can use a converter to specify the type of the argument like{variable_name:converter}.Converter types:str(default) accepts any text without a slashintaccepts positive integersfloataccepts positive floating point valuespathlike string but also accepts slashesuuidaccepts UUID stringsConvertors are used by prefixing them with a colon, like so:@router.route('/orders/{order_id:int}')deforders():return'result from the fn'Any unknown convertor will be parsed as a regex:@router.route('/orders/{order_id:\d{3}}')deforders():return'result from the fn'Multiple paths are supported as well:@router.route('/','/home')defindex():return'index'Handling HTTP methods:@router.route('/only-post',methods=['POST'])defonly_post():return'only-post'Submounting routes:subrouter=Router()@subrouter.route('/items/{item}')defitems():passrouter=Router()router.route('/api')(subrouter)match=router('/api/items/12',method='GET')assertmatch,'HTTP path is ok'assertmatch.targetisitemsassertmatch.params=={"item":"12"}Bug trackerIf you have any suggestions, bug reports or
annoyances please report them to the issue tracker
athttps://github.com/klen/http-router/issuesContributingDevelopment of the project happens at:https://github.com/klen/http-routerLicenseLicensed under aMIT license.
Package: httprunner-ex
HttpRunnerHttpRunneris a simple & elegant, yet powerful HTTP(S) testing framework. Enjoy! ✨ 🚀 ✨Design PhilosophyEmbrace open source, stand on giants' shoulders, likeRequests,unittestandLocust.Convention over configuration.Pursuit of high rewards, write once and achieve a variety of testing needsKey FeaturesInherit all powerful features ofRequests, just have fun to handle HTTP(S) in human way.Define testcases in YAML or JSON format in concise and elegant manner.Record and generate testcases withHARsupport. seehar2case.Supportsvariables/extract/validatemechanisms to create full test scenarios.Supports perfect hook mechanism.Withdebugtalk.pyplugin, very easy to implement complex logic in testcase.Testcases can be run in diverse ways, with single testcase, multiple testcases, or entire project folder.Test report is concise and clear, with detailed log records.With reuse ofLocust, you can run performance test without extra work.CLI command supported, perfect combination withCI/CD.DocumentationHttpRunner is rich documented.中文用户使用手册开发历程记录博客CHANGELOG
Package: httpsec
HTTP SEC初衷作为最原始的http客户端 我希望能获取到最终发送的内容、也希望能获取最初获取到的内容、但是目前没有公开库对这种需求做了兼容作为网络安全从业者、他们常常会发送一些不符合规则、复杂的url如http://localhost./../api
http://localhost/?doAs=`whoami`无论是request还是urllib3都会进行转义、而更底层的http.client则会直接InvalidURL 而对其源码进行path影响范围不可控Coding
Package: httpself
httpselfHTTP server over SSL/TLS with an automatically generated self-signed certificate.UsageServe static files from the current working directory:$https[-p/--port<NNNN>][--public]Example #1By default, the server runs on port number443, which requires superuser privileges. Note that the server will only be accessible from thelocalhost:$https
Runningserverathttps://localhost:443Example #2To specify an alternative port number:$https--port8443Runningserverathttps://localhost:8443Example #3To make the server accessible from other devices:$https--public
Runningserverathttps://0.0.0.0:443Example #4To run the server publicly on a custom port:$https--public-p8443Runningserverathttps://0.0.0.0:8443Installation$pipinstallhttpself
Package: httpserver
Python 3.4 asyncio implementation of an HTTP serverFree software: BSD licenseDocumentation:http://pythonhosted.org/httpserver/FeaturesSupports HTTP/1.1Supports Keep-AliveServe a specific hostname onlyBind to an ip addressUses asyncioInstalls an ‘httpserver’ commandHistory1.1.0 (2015-04-02)No longer rely on sockets to timeout themselvesAdd default timeout of 15 seconds to httpserverNegotiate with the Keep-Alive headerAdd--versioncommandChange documentation theme toalabaster1.0.1 (2015-03-21)Fix small issue in README on pypi1.0.0 (2015-03-21)First release
Package: httpserver4u
Simple HTTP Server一个支持文件上传下载和临时文本保存的 HTTP 服务器。安装：pip3 install httpserver4u运行：python3 -m httpserver4u不需安装运行：python src/httpserver4u/server.py代码（单脚本即可执行）无三方库依赖。适用于 Python 3.6 及以上版本。基于UniIsland 的 Gist和Tallguy297/SimpleHTTPServerWithUpload的代码，稍作修改：移除了图标解决了 Ctrl-C 退出后立刻重启，提示port already in use的问题增加文本保存功能完全 UTF-8 化（除二进制文件下载/上传外）适用：临时、局域网内、小文件不适用：长时间运行、大文件量、高并发、面向外部网络开放、需要安全性保证A simple HTTP server with file upload/download and quick text save function.Install：pip3 install httpserver4uRun：python3 -m httpserver4uRun without install：python src/httpserver4u/server.pysource code(This script contains all functionality.)No third-party dependency. Python 3.6 or newer version required.Based on code ofUniIsland's GistandTallguy297/SimpleHTTPServerWithUpload, with slight modification for my own use case:Removes the iconsFix the bug that if the script is stopped using Ctrl-C and immediately restarted, it will fail withport already in useAdd the ability to quickly save text to a text fileEnable UTF-8 encoding everywhere (beside actual binary file download / upload)For: temporary, local lan network, small filesNot for: long term, large file, high concurrency, exposed to external network, security needed
Package: http-server-base
HTTP Server BaseThis project is a Tornado-based HTTP-server base for easier development.
The repository also includes a very simple example server.FeaturesEasy deployment;Implemented logging;Automated Request Id generation;Implemented configuration loading;Methods for proxying requests.InstallationRequirementsPlease, note, that Python 3.6.0+ is required for this tool.Installation with PyPIpython3.6-mpipinstallhttp-server-baseManual InstallationClone the repositoryRun as sudo/admin:python3.6 -m pip install -e .Import to your project:import http_server_baseUsageStarting Simple ServerYou can start simple HTTP server that logs all requests via console:python3.6-mhttp_server_base[port][arguments]Default port is 80 if allowed, else 8080
Arguments should be passed in formatname=valueUseful LinksTornado Project PagePython 3.6.0 Release Notes
Package: httpservermock
httpservermockhttpservermockprovides a HTTP server mock that can be used to test code that needs to interact with an HTTP server.pipinstallhttpservermock# orpoetryadd--devhttpservermockExample usage:fromurllib.errorimportHTTPErrorfromurllib.requestimporturlopenimportpytestfromhttpservermockimportMethodName,MockHTTPResponse,ServedBaseHTTPServerMockdeftest_example()->None:withServedBaseHTTPServerMock()ashttpmock:httpmock.responses[MethodName.GET].append(MockHTTPResponse(404,"Not Found",b"gone away",{}))httpmock.responses[MethodName.GET].append(MockHTTPResponse(200,"OK",b"here it is",{}))# send a request to get the first responsewithpytest.raises(HTTPError)asraised:urlopen(f"{httpmock.url}/bad/path")assertraised.value.code==404# get and validate request that the mock receivedreq=httpmock.requests[MethodName.GET].pop(0)assertreq.path=="/bad/path"# send a request to get the second responseresp=urlopen(f"{httpmock.url}/")assertresp.status==200assertresp.read()==b"here it is"httpmock.responses[MethodName.GET].append(MockHTTPResponse(404,"Not Found",b"gone away",{}))httpmock.responses[MethodName.GET].append(MockHTTPResponse(200,"OK",b"here it is",{}))
Package: http-server-mock
http-server-mock is a HTTP Server Mock using Flask. You can use it to test possible integrations with your application.http-server-mock is available on PyPI. To install it just run:pip install http-server-mockUsing http-server-mock is similar to implement any Flask application.fromhttp_server_mockimportHttpServerMockimportrequestsapp=HttpServerMock(__name__)@app.route("/",methods=["GET"])defindex():return"Hello world"withapp.run("localhost",5000):r=requests.get("http://localhost:5000/")# r.status_code == 200# r.text == "Hello world"HttpServerMock will use a random route to know if the http server is running, if you want to set a specific route to do it just set the parameter is_alive_route:fromhttp_server_mockimportHttpServerMockapp=HttpServerMock(__name__,is_alive_route="/is-alive")
Package: http-servers
http-servers: static HTTP server CLIhttp-servers is a simple, no-dependencies command-line static HTTP server.PurposesSimilar to node.js http-server, but without the need to install nodeThis package doesn't bring additional dependenciesInstallationpipinstallhttp-serversDocumentation - RTF(riendly)M$ http-server --help
usage: http-server [--cors] [-h HOST] [-p PORT] [-d SOURCE_DIR] [--cache] [--help]

Run HTTP server in given folder

optional arguments:
  --cors                Pass this flag to enable cors
  -h HOST, --host HOST  Address on which server will listen
  -p PORT, --port PORT  Port on which server will listen
  -d SOURCE_DIR, --source-dir SOURCE_DIR
  --cache               Watch changes in directory and invalidate cache on change.
  --help                Show this help
Package: http-session
http_sessionis the foundation of a session management system.
The provided prototypes allow implementations using a wide array of
backends.http_sessionrelies on three components:The “store” prototyped inhttp_session.meta.Storerepresents a store handling sessions. This store knows how to
retrieve, persist, clear or create sessions, using their SID.The “session” implemented inhttp_session.session.Sessionrepresents
the session iself. It is discriminated by its sid and is able to set
and get key/value pairs and track the modifications and accesses.The “manager” oversees the store and session, in order to interface
them with the browser. It is mainly used as a SID policy and middleware.
A functional implementation using secure cookies is provided inhttp_session.cookie.SignedCookieManager.Changelog0.2 (2021-11-08)Invalid time signature now trigger the generation of a new cookie.0.1 (2021-11-08)Fork-evolution fromcromlech.session
Package: http-sf
HTTP Structured Fields in PythonThis is aPython 3library implementing parsing and serialisation ofRFC8941.This library also implements Display Strings and Dates, as specified indraft-ietf-httpbis-sfbis-05.Python APIParsingTextual HTTP headers can be parsed by callingparse; the return value is a data structure that represents the field value.>>>fromhttp_sfimportparse,ser>>>parse(b"foo; a=1, bar; b=2",tltype="dictionary"){'foo':(True,{'a':1}),'bar':(True,{'b':2})}parse()takes a bytes-like object as the first argument. If you want to parse a string, please.encode()it first.Indicating Top-Level TypeBecause the library needs to know which kind of field it is, you need to hint this when callingparse. There are two ways to do this:Using atltypeparameter, whose value should be one of 'dictionary', 'list', or 'item'.Using anameparameter to indicate a field name that has a registered type, perthe retrofit draft.Note that if you usename, aKeyErrorwill be raised if the type associated with the name isn't known, unless you also pass atltypeas a fallback.TypesIn the returned data, Dictionaries are represented as Python dictionaries; Lists are represented as Python lists, and Items are the bare type.Bare types are represented using the following Python types:Integers:intDecimals:floatStrings:strTokens:http_sf.Token(aUserString)Byte Sequences:bytesBooleans:boolDates:datetime.datetimeDisplay Strings:http_sf.DisplayString(aUserString)Inner Lists are represented as lists as well.ParametersStructured Types that can have parameters (including Dictionary and List members as well as singular Items and Inner Lists) are represented as a tuple of(value, parameters)where parameters is a dictionary.So, a single item that's a Token with one parameter whose value is an integer will be represented like this:>>>parse(b"foo; a=1",tltype="item")(Token("foo"),{'a':1})Note that even if there aren't parameters, a tuple will still be returned, as in some items on this List:>>>parse(b"a, b; q=5, c",tltype="list")[(Token("a"),{}),(Token("b"),{'q':5}),(Token("c"),{})]SerialisationTo serialise that data structure back to a textual Structured Field, useser:>>>field=parse(b"a, b; q=5, c",tltype="list")>>>ser(field)'a, b;q=5, c'When usingser, if an Item or Inner List doesn't have parameters, they can be omitted; for example:>>>structure=[5,6,(7,{"with":"param"})]>>>ser(structure)'5, 6, 7;with="param"'Note thatserproduces a string, not a bytes-like object.Command Line UseYou can validate and examine the data model of a field value by calling the library on the command line, using-d,-land-ito denote dictionaries, lists or items respectively; e.g.,>python3-mhttp_sf-i"foo;bar=baz"[{"__type":"token","value":"foo"},{"bar":{"__type":"token","value":"baz"}}]or:>python3-mhttp_sf-i"foo;&bar=baz"FAIL:Keydoesnotbeginwithlcalphaor*at:&bar=bazAlternatively, you can pass the field name with the-noption, provided that it is a compatible retrofit field:>python3-mhttp_sf-n"Cache-Control""max-age=40, must-revalidate"{"max-age":[40,{}],"must-revalidate":[true,{}]}Note that if successful, the output is in the JSON format used by thetest suite.
Package: http_signature
Sign http requests with secure signatures.RequirementsPyCryptoOptional:ssh or paramiko >= 1.8.0 (for ssh-agent integration)requestsUsagefor simple raw signing:import http_signature

sig_maker = http_signature.Signer(secret='test.pem', algorithm='rsa-sha256')
sig_maker.sign('hello world!')for use with requests:import json
import requests
from http_signature.requests_auth import HTTPSignatureAuth

auth = HTTPSignatureAuth(key_id='Test', secret='test.pem')
z = requests.get('https://api.joyentcloud.com/my/packages/Small+1GB',
                         auth=auth, headers={'X-Api-Version': '~6.5'})Class initialization parametershttp_signature.Signer(secret='', algorithm='rsa-sha256', allow_agent=False)secret, in the case of an rsa signature, is a path to a private RSA pem file. In the case of an hmac, it is a secret password.algorithmis one of the six allowed signatures:rsa-sha1,rsa-sha256,rsa-sha512,hmac-sha1,hmac-sha256,hmac-sha512.allow_agentuses thesshpackage to find anssh-agentinstance running, and uses that to sign all requests. Note that if so, this overrides manual selection of the signing algorithm torsa-sha1.http_signature.requests_auth.HTTPSignatureAuth(key_id='', secret='', algorithm='rsa-sha256', headers=None, allow_agent=False)key_idis the label by which the server system knows your RSA signature or password.headersis the list of HTTP headers that are concatenated and used as signing objects. By default it is the specification’s minimum, theDateHTTP header.secret,algorithm, andallow_agentare as above.LicenseMITChanges0.1.4 (2012-10-03)Account for ssh now being re-merged into paramiko: either package is acceptable (but paramiko should ideally be >= 1.8.0)0.1.3 (2012-10-02)Stop enablingallow_agentby defaultStop requiringsshpackage by default – it is imported only whenallow_agent=TrueChanged logic around ssh-agent: if one key is available, don’t bother with any other authentication methodChanged logic around key file usage: if decryption fails, prompt for passwordBug fix: ssh-agent resulted in a nonsensical error if it found no correct keys (thanks, petervolpe)Introduce versioneer.py
Package: httpsig-pure-hmac
Fork of Adam Knight’shttpsig, providing the same functionality, except that:RSA is not supported.PyCrypto is not required.This package is intended as a lightweight option for HMAC-only clients.RequirementsPython 2.7, 3.3+sixUsageimporthttpsig_pure_pythonashttpsigSeeoriginal packagefor more info.httpsig Changes1.1.2 (2015-Feb-11)HMAC verification is now constant-time.1.1.1 (2015-Feb-11)(pulled)1.1.0 (2014-Jul-24)Changed “(request-line)” to “(request-target)” to comply with Draft 3.1.0.3 (2014-Jul-09)Unified the default signing algo under one setting. Setting httpsig.sign.DEFAULT_SIGN_ALGORITHM changes it for all future instances.Handle invalid params a little better.1.0.2 (2014-Jul-02)Ensure we treat headers as ASCII strings.Handle a case in the authorization header where there’s garbage (non-keypairs) after the method name.1.0.1 (2014-Jul-02)Python 3 support (2.7 + 3.2-3.4)Updated tox and Travis CI configs to test the supported Python versions.Updated README.1.0.0 (2014-Jul-01)Written againsthttp://tools.ietf.org/html/draft-cavage-http-signatures-02Added “setup.py test” and tox support.Added sign/verify unit tests for all currently-supported algorithms.HeaderSigner and HeaderVerifier now share the same message-building logic.The HTTP method in the message is now properly lower-case.Resolved unit test failures.Updated Verifier and HeaderVerifier to handle verifying both RSA and HMAC sigs.Updated versioneer.Updated contact/author info.Removed stray keypair in test dir.Removed SSH agent support.Removed suport for reading keyfiles from disk as this is a huge security hole if this is used in a server framework like drf-httpsig.1.0b1 (2014-Jun-23)Removed HTTP version from request-line, per spec (breaks backwards compatability).Removed auto-generation of missing Date header (ensures client compatability).http-signature (previous)0.2.0 (unreleased)Update to newer spec (incompatible with prior version).Handlerequest-linemeta-header.Allow secret to be a PEM encoded string.Add test cases from spec.0.1.4 (2012-10-03)Account for ssh now being re-merged into paramiko: either package is acceptable (but paramiko should ideally be >= 1.8.0)0.1.3 (2012-10-02)Stop enablingallow_agentby defaultStop requiringsshpackage by default – it is imported only whenallow_agent=TrueChanged logic around ssh-agent: if one key is available, don’t bother with any other authentication methodChanged logic around key file usage: if decryption fails, prompt for passwordBug fix: ssh-agent resulted in a nonsensical error if it found no correct keys (thanks, petervolpe)Introduce versioneer.py
Package: httpsigpy
HTTP Message SignaturesThis library implements HTTP Message Signatures. The underlying crypto is provided by PyCryptodomex.Pypi Page:https://pypi.org/project/httpsigpy/Usage:fromhttpsigimport*SigningTo sign an HTTP message, first it has to be parsed into its message components:msg=event['body'].encode('utf-8')components=parse_components(msg)This provides a data structure with each possible message component indexed by its name, identifier, and value.To create the signature input, pass in the parsed components structure as well as a list of components to sign, with the signature parameters:siginput=generate_input(components,(# covered components list{'id':"@method"},{'id':"@authority"},{'id':"@path"},{'id':"content-digest"},{'id':"content-length"},{'id':"content-type"}),{'created':1618884473,'keyid':'test-key-rsa-pss'})base=siginput['signatureInput']sigparams=siginput['signatureParams']This outputs abasestring that can be passed to the signer.key=RSA.import_key(PKCS8.unwrap(PEM.decode(rsaTestKeyPssPrivate)[0])[1])h=SHA512.new(base.encode('utf-8'))signer=pss.new(key,mask_func=mgf512,salt_bytes=64)signed=http_sfv.Item(signer.sign(h))VerifyTo verify an HTTP message, first it has to be parsed into its message components:msg=event['body'].encode('utf-8')components=parse_components(msg)This provides a data structure with each possible message component indexed by its name, identifier, and value.To create the signature input, pass in the parsed components structure as well as a list of components to sign, and the signature parameters.siginput=generate_input(components,(# covered components list{'id':"@method"},{'id':"@authority"},{'id':"@path"},{'id':"content-digest"},{'id':"content-length"},{'id':"content-type"}),{'created':1618884473,'keyid':'test-key-rsa-pss'})This can be passed to the verifier function:h=SHA512.new(base.encode('utf-8'))pubKey=RSA.import_key(rsaTestKeyPssPublic)verifier=pss.new(pubKey,mask_func=mgf512,salt_bytes=64)try:verified=verifier.verify(h,signed.value)print('> YES!')except(ValueError,TypeError):print('> NO!')