PyWSGIRef 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
PyWSGIRef/__init__.py ADDED
@@ -0,0 +1,81 @@
1
+ """
2
+ PYWSGIREF
3
+ """
4
+ from typing import Callable
5
+ import requests
6
+ from wsgiref.simple_server import make_server, WSGIServer
7
+
8
+ from .exceptions import *
9
+ from .pyhtml import PyHTML
10
+ from .defaults import *
11
+
12
+ def about():
13
+ """
14
+ Returns information about your release and other projects by LK
15
+ """
16
+ return {"Version":(1, 0, 0), "Author":"Leander Kafemann", "date":"07.06.2025",\
17
+ "recommend":("Büro by LK", "pyimager by LK", "naturalsize by LK"), "feedbackTo": "leander@kafemann.berlin"}
18
+
19
+ SCHABLONEN = {}
20
+ finished = False
21
+
22
+ def loadFromWeb(url: str, data: dict = {}) -> str:
23
+ """
24
+ Loads content from the given URL with the given data.
25
+ """
26
+ if finished:
27
+ raise ServerAlreadyGeneratedError()
28
+ if not url.endswith(".pyhtml"):
29
+ raise InvalidFiletypeError()
30
+ rq = requests.post(url, data).content
31
+ return rq.decode()
32
+
33
+ def loadFromFile(filename: str) -> str:
34
+ """
35
+ Loads a file from the given filename.
36
+ """
37
+ if finished:
38
+ raise ServerAlreadyGeneratedError()
39
+ if not filename.endswith(".pyhtml"):
40
+ raise InvalidFiletypeError()
41
+ with open(filename, "r", encoding="utf-8") as f:
42
+ content = f.read()
43
+ return content
44
+
45
+ def addSchablone(name: str, content: str):
46
+ """
47
+ Adds a template to the SCHABLONEN dictionary.
48
+ """
49
+ global SCHABLONEN
50
+ SCHABLONEN += {name: PyHTML(content)}
51
+
52
+ def makeApplicationObject(contentGeneratingFunction: Callable) -> Callable:
53
+ """
54
+ Returns a WSGI application object based on your contentGeneratingFunction.
55
+ The contentGeneratingFunction should take a single argument (the path) and return the content as a string.
56
+ """
57
+ if not callable(contentGeneratingFunction):
58
+ raise InvalidCallableError()
59
+ def simpleApplication(environ, start_response) -> list:
60
+ """
61
+ A simple WSGI application object that serves as a template.
62
+ """
63
+ type_ = "text/html"
64
+ status = "200 OK"
65
+ content = contentGeneratingFunction(environ["PATH_INFO"])
66
+ headers = [("Content-Type", type_),
67
+ ("Content-Length", str(len(content))),
68
+ ('Access-Control-Allow-Origin', '*')]
69
+ start_response(status, headers)
70
+ return [content.encode("utf-8")]
71
+ return simpleApplication
72
+
73
+ def setUpServer(application: Callable) -> WSGIServer:
74
+ """
75
+ Creates a WSGI server.
76
+ No additional Schablonen can be loaded from the web.
77
+ """
78
+ global finished
79
+ finished = True
80
+ server = make_server('', 8000, application)
81
+ return server
PyWSGIRef/__main__.py ADDED
@@ -0,0 +1,53 @@
1
+ """
2
+ Set up and run the PyWSGIRef server with a simple HTML response.
3
+ """
4
+ from PyWSGIRef import *
5
+
6
+ def main():
7
+ """
8
+ Main function to set up and run the PyWSGIRef server.
9
+ """
10
+ # define main html response
11
+ MAIN_HTML = """<!DOCTYPE html>
12
+ <html lang="de">
13
+ <head>
14
+ <meta charset="UTF-8">
15
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
16
+ <title>PyWSGIRef Server</title>
17
+ </head>
18
+ <body>
19
+ <h1>Willkommen zum PyWSGIRef Server!</h1>
20
+ <p>Dies ist die Hauptseite des Servers.</p>
21
+ <p>Sie nutzen Version {} von PyWSGIRef.</p>
22
+ </body>
23
+ </html>"""
24
+
25
+ # add Schablone 'Hallo Welt' as main
26
+ addSchablone("main", MAIN_HTML)
27
+
28
+ # set up application object
29
+ def contentGenerator(path: str) -> str:
30
+ """
31
+ Serves as the main WSGI application.
32
+ """
33
+ match path:
34
+ case "/":
35
+ content = SCHABLONEN["main"].decoded().format(about()["Version"])
36
+ case "/hello":
37
+ content = HELLO_WORLD
38
+ case _:
39
+ content = ERROR
40
+ return content
41
+
42
+ # make the application object
43
+ application = makeApplicationObject(contentGenerator)
44
+
45
+ # set up server
46
+ server = setUpServer(application)
47
+ server.serve_forever()
48
+
49
+ # Note: This code is intended to be run as a script, not as a module.
50
+ print("Successfully started WSGI server on port 8000.")
51
+
52
+ if __name__ == "__main__":
53
+ main()
PyWSGIRef/defaults.py ADDED
@@ -0,0 +1,14 @@
1
+ HELLO_WORLD = """<!DOCTYPE html>
2
+ <html lang"de">
3
+ <body>
4
+ <h1>Hallo Welt!</h1>
5
+ </body>
6
+ <html>"""
7
+
8
+ ERROR = """<!DOCTYPE html>
9
+ <html lang"de">
10
+ <body>
11
+ <h1>Fehler!</h1>
12
+ <p>Es ist ein Fehler aufgetreten.</p>
13
+ </body>
14
+ </html>"""
@@ -0,0 +1,24 @@
1
+ class ServerAlreadyGeneratedError(Exception):
2
+ """
3
+ Raised when a server is already generated,
4
+ so that further modifications are not allowed.
5
+ """
6
+ def __init__(self, message="Server has already been generated."):
7
+ self.message = message
8
+ super().__init__(self.message)
9
+
10
+ class InvalidFiletypeError(Exception):
11
+ """
12
+ Raised when an invalid file type (not PyHTML) is encountered.
13
+ """
14
+ def __init__(self, message="Invalid file type. Only .pyhtml files are allowed."):
15
+ self.message = message
16
+ super().__init__(self.message)
17
+
18
+ class InvalidCallableError(Exception):
19
+ """
20
+ Raised when a callable is expected but not provided.
21
+ """
22
+ def __init__(self, message="Expected a callable object."):
23
+ self.message = message
24
+ super().__init__(self.message)
PyWSGIRef/pyhtml.py ADDED
@@ -0,0 +1,16 @@
1
+ from .defaults import HELLO_WORLD as DEFAULT
2
+
3
+ class PyHTML:
4
+ def __init__(self, html: str = DEFAULT):
5
+ self.html = html
6
+ def decode(self):
7
+ """
8
+ Decodes the HTML content.
9
+ """
10
+ self.html = self.html.strip()
11
+ def decoded(self) -> str:
12
+ """
13
+ Returns the decoded HTML content.
14
+ """
15
+ self.decode()
16
+ return self.html
@@ -0,0 +1,118 @@
1
+ Metadata-Version: 2.4
2
+ Name: PyWSGIRef
3
+ Version: 1.0.0
4
+ Summary: display colors in console
5
+ Author-email: Leander Kafemann <leander@kafemann.berlin>
6
+ Project-URL: Homepage, https://github.com/LeanderKafemann/PyWSGIRef
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.11
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: requests
14
+ Requires-Dist: typing
15
+ Dynamic: license-file
16
+
17
+ # PyWSGIRef
18
+ easy server-setup
19
+ ## Advantage
20
+ Many web services offer simple ways to set up a WSGI webserver.<br/>
21
+ The built-in WSGI server in Python is, however, not very easy to use.<br/>
22
+ PyWSGIRef provides a simple way to set up a WSGI server with minimal code.<br/><br/>
23
+ Also, a problem with many of those web services is that they aren't able to make web requests<br/>
24
+ and it's very slow to read files once the server is running.<br/>
25
+ PyWSGIRef solves this problem by providing a simple way to load PyHTML files from the web or from the local filesystem<br/>
26
+ before the server is running.<br/><br/>
27
+ PyHTML files are HTML files that can contain {}-s for Python formatting or<br/>
28
+ (upcoming) code blocks or shortened HTML, which can be used to create dynamic HTML content.<br/>
29
+ PyWSGIRef also provides a simple way to decode these.
30
+ ## Installation
31
+ ### Using *pip*
32
+ You can install PyWSGIRef via pip using
33
+ <li>in a commandline:</li><br/>
34
+
35
+ ```bash
36
+ py -m pip install PyWSGIRef
37
+ ```
38
+ <br/>
39
+ <li>in a python script:</li><br/>
40
+
41
+ ```python
42
+ import os
43
+ os.system('py -m pip install PyWSGIRef')
44
+ ```
45
+ ## Usage
46
+ ### Setting up the WSGI server
47
+ ```python
48
+ from PyWSGIRef import *
49
+
50
+ # Create a WSGI application object
51
+ def simple_app(path: str) -> str:
52
+ return f"Hello, you visited {path}!"
53
+ application = makeWSGIApp(simple_app)
54
+
55
+ # Create a WSGI server
56
+ server = makeWSGIServer(application, port=8000)
57
+ server.serve_forever()
58
+ ```
59
+ The <code>makeWSGIApp</code> function requires a callable that takes a single argument (the path) and returns a string response.<br/>
60
+ The <code>makeWSGIServer</code> function creates a WSGI server that listens on the specified port (default is 8000)<br/>
61
+ and calls the application object with the environ.<br/>
62
+ You can also use your own application object instead of the one created by <code>makeWSGIApp</code>.
63
+ ### Loading PyHTML
64
+ PyWSGIRef also provides a simple way to load PyHTML files:
65
+ ```python
66
+ from PyWSGIRef import *
67
+
68
+ # load from file
69
+ html = loadFromFile('index.pyhtml')
70
+
71
+ # load from web
72
+ html = loadFromWeb('https://example.com/index.pyhtml')
73
+ ```
74
+ This is useful for serving dynamic HTML content in your WSGI application.<br/>
75
+ The funcs are callable unless you set up a server.
76
+ ### Using Templates
77
+ PyWSGIRef also provides a simple way to use templates in your WSGI application:
78
+ ```python
79
+ from PyWSGIRef import *
80
+
81
+ # add template to template dictionary
82
+ # -> saves as PyHTML object
83
+ addSchablone("index", loadedPyHTMLFile)
84
+
85
+ # load template from dictionary
86
+ # get HTML code from PyHTML object
87
+ html = SCHABLONEN["index"].decoded()
88
+ # use Python formatting
89
+ serverPageContent = html.format("Hello, World!")
90
+ ```
91
+ Note that you may only use the <code>addSchablone</code> function before you set up a server.
92
+ ### Default HTML templates
93
+ PyWSGIRef comes with some default HTML templates that you can use in your WSGI application.<br/>
94
+ You can access them via the <code>PyWSGIRef.defaults</code>:
95
+ ```python
96
+ from PyWSGIRef import *
97
+
98
+ # load default HTML template
99
+ addSchablone("hello", HELLO_WORLD)
100
+ addSchablone("error", ERROR)
101
+ ```
102
+ ### __main__ script
103
+ You may produce a simple WSGI server by using either:<br/>
104
+ ```python
105
+ from PyWSGIRef import *
106
+
107
+ main()
108
+ ```
109
+ or (from a commandline)
110
+ ```bash
111
+ py -m PyWSGIRef
112
+ ```
113
+ ### Others
114
+ Use the following to get information about your release and the author of the module:
115
+ ```python
116
+ pycols.about()
117
+ ```
118
+ ### More coming soon
@@ -0,0 +1,10 @@
1
+ PyWSGIRef/__init__.py,sha256=50HmwqTPS6OqdYqofB3TsMO5NTqahc46XB64oy0enhU,2622
2
+ PyWSGIRef/__main__.py,sha256=YE0N5gh8YnoKYnrx16ndUJMqe8duRGh6N-K5nRbjRnA,1569
3
+ PyWSGIRef/defaults.py,sha256=0-wgGBN-E1mAfRu02e9NfMyen_9tlpMYmEDVjrbKGYA,272
4
+ PyWSGIRef/exceptions.py,sha256=jInWesq5LCHOHM9dSTBirPlxi7czNY0eUL9dF1VS8Qo,846
5
+ PyWSGIRef/pyhtml.py,sha256=gz5Yd6_KIMQmmQaZ2IlBOwsplLy-MbiTZHihZfeNcJg,405
6
+ pywsgiref-1.0.0.dist-info/licenses/LICENSE,sha256=qTCL_CFEFDks866k8DC3YUBOuhTxeRrLQTa2M5tBBbU,1094
7
+ pywsgiref-1.0.0.dist-info/METADATA,sha256=I34xh3rkXW1RL052wdxECRWY8W8bqX4PB38DFAmYeds,3976
8
+ pywsgiref-1.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
+ pywsgiref-1.0.0.dist-info/top_level.txt,sha256=l4O5G2iK3imgNb3ObU47g2cXYR6b2ibpv71Dxwwi2As,10
10
+ pywsgiref-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Leander Kafemann
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ PyWSGIRef