[projects/pld-ftp-admin] web: port the CGI interface to Python 3

arekm arekm at pld-linux.org
Sat Oct 24 11:46:34 CEST 2026


commit bf9c2e3e7605d42228185e117e076a344141c2df
Author: Arkadiusz Miśkiewicz <arekm at maven.pl>
Date:   Tue Oct 20 15:40:24 2026 +0200

    web: port the CGI interface to Python 3
    
    Run it as a WSGI app through wsgiref; the cgi module is gone in 3.13.

 cgi-bin/index.py    |  56 ++++++++++---------------
 modules/user.py     |  26 ++++--------
 modules/wwwcmds.py  |  14 +++----
 modules/wwwiface.py | 119 +++++++++++++++++++++-------------------------------
 4 files changed, 83 insertions(+), 132 deletions(-)
---
diff --git a/cgi-bin/index.py b/cgi-bin/index.py
index 274a474..c729c66 100755
--- a/cgi-bin/index.py
+++ b/cgi-bin/index.py
@@ -1,45 +1,31 @@
 #!/usr/bin/env python3
-# vi: encoding=utf-8 ts=8 sts=4 sw=4 et
+# vi: ts=8 sts=4 sw=4 et
 
-from __future__ import print_function
-
-# Printing errors (no SyntaxErrors though, but that's not a problem)
-import sys, os
-sys.stderr=sys.stdout
-
-contenttypesent=False
-
-def myexceptionhandler(type, value, traceback):
-    if contenttypesent:
-        print('<pre>')
-        sys.__excepthook__(type, value, traceback)
-        print('</pre>')
-    else:
-        print("Content-Type: text/plain\n")
-        sys.__excepthook__(type, value, traceback)
-    sys.exit(1)
-
-sys.excepthook=myexceptionhandler
-# End printing errors
+import sys
+from wsgiref.handlers import CGIHandler
 
 sys.path.insert(0, '../modules')
 
-import wwwiface, user
+import user
+import wwwcmds
+import wwwiface
+
 
-opts, cks = wwwiface.getopts()
-u=user.User(cks, opts)
+def application(environ, start_response):
+    opts, cks = wwwiface.getopts(environ)
+    page = wwwiface.Page()
+    u = user.User(cks, opts, page)
 
-if u.loggedin:
-    wwwiface.addheader('Logged in: '+u.login)
-    wwwiface.addmenu(file='loggedinmenu')
-    import wwwcmds
-    wwwcmds.handlecmds(opts)
-else:
-    wwwiface.addheader('Login form')
-    wwwiface.addcontent(file='regform')
+    if u.loggedin:
+        page.addheader('Logged in: ' + u.login)
+        page.addmenu(file='loggedinmenu')
+        wwwcmds.handlecmds(opts, page)
+    else:
+        page.addheader('Login form')
+        page.addcontent(file='regform')
 
-wwwiface.sendhttpheaders()
-contenttypesent=True
+    start_response('200 OK', page.headers)
+    return [page.render()]
 
-wwwiface.sendhtml()
 
+CGIHandler().run(application)
diff --git a/modules/user.py b/modules/user.py
index 7f41958..65135ed 100644
--- a/modules/user.py
+++ b/modules/user.py
@@ -1,16 +1,14 @@
-# vi: encoding=utf-8 ts=8 sts=4 sw=4 et
+# vi: ts=8 sts=4 sw=4 et
 
-from __future__ import print_function
+import ftpio
 
-import Cookie, time, ftpio
-
-UserNotLoggedIn="UserNotLoggedIn"
 
 class User:
-    def __init__(self, cookies, options):
+    def __init__(self, cookies, options, page):
         self.loggedin=False
+        self.page=page
         ftpio.connect('wwwiface')
-	if 'ftpsessid' in cookies and cookies['ftpsessid']:
+        if cookies.get('ftpsessid'):
             self.login=ftpio.login_cookie(cookies['ftpsessid'])
             if self.login:
                 self.loggedin=True
@@ -28,19 +26,9 @@ class User:
         if self.cookie:
             self.login=options['login']
             self.loggedin=True
-            C = Cookie.SimpleCookie()
-            C['ftpsessid']=self.cookie
-            #C['ftpsessid']['expires']=time.strftime(
-                                        #"%a, %d-%b-%y %H:%M:%S GMT",
-                                        #time.gmtime(time.time()+86400))
-            print(C)
+            self.page.setcookie('ftpsessid', self.cookie)
 
     def logout(self):
         self.loggedin=False
         ftpio.logout()
-        C = Cookie.SimpleCookie()
-        C['ftpsessid']=''
-        C['ftpsessid']['expires']=time.strftime("%a, %d-%b-%y %H:%M:%S GMT",
-                                    time.gmtime(time.time()-31536000))
-        print(C)
-
+        self.page.setcookie('ftpsessid', '', expires=-31536000)
diff --git a/modules/wwwcmds.py b/modules/wwwcmds.py
index ea6c63c..e3108c4 100644
--- a/modules/wwwcmds.py
+++ b/modules/wwwcmds.py
@@ -1,9 +1,9 @@
 # vi: encoding=utf-8 ts=8 sts=4 sw=4 et
 
-import wwwiface, ftpio
+import ftpio
 
 
-def handlecmds(options):
+def handlecmds(options, page):
     def chkbox(pkgname, value):
         retval='<input type="checkbox" name="%s"' % pkgname
         if value:
@@ -14,12 +14,12 @@ def handlecmds(options):
     if 'action' in options and options['action'] in actions:
         pass
     else:
-        wwwiface.addcontent('<form action="index.py" method="post"><table border="1">')
-        wwwiface.addcontent('<tr><td>Mv</td><td>Rm</td><td>Package</td></tr>')
+        page.addcontent('<form action="index.py" method="post"><table border="1">')
+        page.addcontent('<tr><td>Mv</td><td>Rm</td><td>Package</td></tr>')
         for pkg in ftpio.gettree():
-            wwwiface.addcontent('<tr><td>%s</td><td>%s</td><td>%s</td></tr>' % (chkbox(pkg[0], pkg[1]), chkbox(pkg[0], pkg[2]), pkg[0]))
-        wwwiface.addcontent('<tr><td> </td><td> </td><td><input type="submit" value="Commit"></td></tr>')
-        wwwiface.addcontent('</table></form>')
+            page.addcontent('<tr><td>%s</td><td>%s</td><td>%s</td></tr>' % (chkbox(pkg[0], pkg[1]), chkbox(pkg[0], pkg[2]), pkg[0]))
+        page.addcontent('<tr><td> </td><td> </td><td><input type="submit" value="Commit"></td></tr>')
+        page.addcontent('</table></form>')
 
 
 actions={}
diff --git a/modules/wwwiface.py b/modules/wwwiface.py
index 4e65630..43f7ff7 100644
--- a/modules/wwwiface.py
+++ b/modules/wwwiface.py
@@ -1,79 +1,56 @@
-# vi: encoding=utf-8 ts=8 sts=4 sw=4 et
+# vi: ts=8 sts=4 sw=4 et
 
-from __future__ import print_function
+from http.cookies import SimpleCookie
+from urllib.parse import parse_qsl
 
-import cgi, Cookie, os
+# html/header.html declares it, so browsers also send form data in it
+CHARSET = 'iso-8859-1'
 
-menu=[]
-content=[]
-header=[]
 
 def getfile(file):
-    f=open("../html/" + file + ".html", 'r')
-    s=f.read()
-    f.close()
-    return s
+    with open("../html/" + file + ".html") as f:
+        return f.read()
 
-def catfile(file):
-    f=open("../html/" + file + ".html", 'r')
-    print(f.read())
-    f.close()
-
-def sendhttpheaders():
-    print("Content-Type: text/html\n")
-
-def getopts():
-    form = cgi.FieldStorage()
-    opts = {}
-    for key in form.keys():
-        opts[key] = form[key].value
+def getopts(environ):
+    'Return (form fields, cookies) of a WSGI request'
+    fields = parse_qsl(environ.get('QUERY_STRING', ''), encoding=CHARSET)
+    if environ['REQUEST_METHOD'] == 'POST':
+        length = int(environ.get('CONTENT_LENGTH') or 0)
+        fields += parse_qsl(environ['wsgi.input'].read(length).decode(CHARSET), encoding=CHARSET)
 
     cookies = {}
-
-    if 'HTTP_COOKIE' in os.environ:
-        c = Cookie.SimpleCookie()
-        c.load(os.environ['HTTP_COOKIE'])
-        for key in c.keys():
-            cookies[key] = c[key].value
-
-    return (opts, cookies)
-
-def sendhtml():
-    catfile('header')
-
-    print('<div id="Header">')
-    for i in header:
-        print(i)
-    print('</div>')
-
-    print('<div id="Menu">')
-    for i in menu:
-        print(i)
-    catfile('menufooter')
-    print('</div>')
-
-    print('<div id="Content">')
-    for i in content:
-        print(i)
-    print('</div>')
-   
-    catfile('footer')
-
-def addmenu(text=None, file=None):
-    if text:
-        menu.append(text)
-    else:
-        menu.append(getfile(file))
-
-def addheader(text=None, file=None):
-    if text:
-        header.append(text)
-    else:
-        header.append(getfile(file))
-
-def addcontent(text=None, file=None):
-    if text:
-        content.append(text)
-    else:
-        content.append(getfile(file))
-
+    for key, morsel in SimpleCookie(environ.get('HTTP_COOKIE', '')).items():
+        cookies[key] = morsel.value
+
+    return (dict(fields), cookies)
+
+class Page:
+    def __init__(self):
+        self.headers = [('Content-Type', 'text/html')]
+        self.header = []
+        self.menu = []
+        self.content = []
+
+    def setcookie(self, name, value, expires=None):
+        c = SimpleCookie()
+        c[name] = value
+        if expires is not None:
+            c[name]['expires'] = expires
+        self.headers.append(('Set-Cookie', c[name].OutputString()))
+
+    def addmenu(self, text=None, file=None):
+        self.menu.append(text or getfile(file))
+
+    def addheader(self, text=None, file=None):
+        self.header.append(text or getfile(file))
+
+    def addcontent(self, text=None, file=None):
+        self.content.append(text or getfile(file))
+
+    def render(self):
+        lines = [getfile('header'),
+                 '<div id="Header">', *self.header, '</div>',
+                 '<div id="Menu">', *self.menu, getfile('menufooter'), '</div>',
+                 '<div id="Content">', *self.content, '</div>',
+                 getfile('footer')]
+        return ''.join(line + '\n' for line in lines).encode(CHARSET, 'xmlcharrefreplace')
================================================================

---- gitweb:

http://git.pld-linux.org/gitweb.cgi/projects/pld-ftp-admin.git/commitdiff/e14cb7d4d74f8bdd9368d9645ecaf49593cf6335



More information about the pld-cvs-commit mailing list