Basic HTTP Server not fully working and not throwing errors - python-3.x

I've started to explore HTTP servers in python and i wanted to do something very simple. The idea is just if a client connects to "my ip"/admin it shows his header on the web page, if not it just uses the default do_GET() function.
My code:
#!/usr/bin/env python3
import http.server
import socketserver
class HttpHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == "/admin":
self.wfile.write("This page is for administrators only".encode())
self.wfile.write(str(self.headers).encode())
else:
http.server.SimpleHTTPRequestHandler.do_GET(self)
http_server=socketserver.TCPServer(("",10002),HttpHandler)
http_server.serve_forever()
For some reason i can't see the headers (unless i do a print of the self.headers to show them in the terminal) it isn't even throwing any errors so i'm kinda lost here.
Thanks for the help

Ok so the solution i came up with (for anyone interested or might friend this thread with the same doubts) is this:
#!/usr/bin/env python3
import http.server
import socketserver
class HttpHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == "/admin":
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html> <head><title> Testing </title> </head><body><p> This page is only for administrators</p>"+str(self.headers)+"</body>", "UTF-8"))
else:
http.server.SimpleHTTPRequestHandler.do_GET(self)
http_server=socketserver.TCPServer(("",10001), HttpHandler)
http_server.serve_forever()

Related

flask not responding with template

I am running a flask server in testing but the render_template() method is not responding
Here is my app.py
from flask import Flask, render_template, jsonify, request
from feeders import feeder
app = Flask(__name__)
#app.route("/", methods=["GET", "POST"])
def feed():
if request.method == "GET":
data = feeder.all_feed()
return render_template("feed.html", allfeed=data)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8080)
I am using ThreadPoolExecutor for some of my tasks, here is how the all_feed() method looks like.
def all_feed():
with ThreadPoolExecutor(max_workers=7) as executor:
results = list(executor.map(get_feed, feeder_site_urls.values()))
print(results)
return results
I can see results on the terminal but the template is not rendering.
And yes all my templates are under templates/.
Edit: I can see that the flask is consuming memory (gradually increasing)
Apparently there was a bug in one of my templates
Always remember to run in DEBUG Mode.
Also create a .flaskenv file with following contents
FLASK_APP=app.py
FLASK_ENV=development
FLASK_RUN_PORT=8000
FLASK_RUN_HOST=0.0.0.0
Thanks to one of my friend

How to get resource path in flask-RESTPlus?

I am fairly new at working with flask and flask-RESTPlus. I have the following and it is not clear how can I determine which path was used in the get request?
ns = api.namespace('sample', description='get stuff')
#ns.route(
'/resource-settings/<string:address>',
'/unit-settings/<string:address>',
'/resource-proposals/<string:address>',
'/unit-proposals/<string:address>')
#ns.param('address', 'The address to decode')
class Decode(Resource):
#ns.doc(id='Get the decoded result of a block address')
def get(self, address):
# How do I know what get path was called?
pass
A better solution would be to use the request context. To get the full path, you can do:
from flask import request
def get(self, address):
# How do I know what get path was called?
print(request.full_path)
Through lot's of digging I found that url_for in flask import.
Still feels a bit wonky but I can create a fully qualified link with:
result = api.base_url + url_for('resource-settings', address=id)
So this works and I get the desired results.

Trying to combine flask and guizero

So i was trying flask when i got an funny idea. If i could combine guizero with my server i could make like a console for my simple server. So i began working when i stumbled over 2 problems.
Here's my code:
from flask import Flask, render_template
from guizero import App, PushButton, Text, TextBox
app = Flask(__name__)
app.debug = True
console = App(title='web server')
text_input = "no message"
def message():
text_input = textbox.get
textbox.clear
header = Text(console, text="Web server console", size= 50)
description = Text(console, text="type message here:")
textbox = TextBox(console)
button = PushButton(console, text="send", command=message)
#app.route('/')
def index():
return render_template('index.html', text= text_input)
#app.route('/next')
def next():
return render_template('game.html')
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
app.display()
The template index.html is just simply a paragraph with {{text}}. It does show the "no message" string.
Now i'm experiencing 2 problems with this code.
1: If i run it it only starts the server, but when i run it again it gives the "already in use" error and then opens the gui
2: If i use the gui the website won't update when i push the button, i think because the gui doesnt run in the same instance of the script as the server. And if it does i don't think the debug function works with variables in the script.
running the server on a raspi 3B on ethernet if that is important
i'm very new to flask and html so maybe i won't understand your answer but i'd be glad if you could help
I also am new to Flask but I think you have to make a new thread (either for the Flask app or the GUI). This makes sure that both Flask and the GUI can run simultaneously. Now you try to run two loops at the same time and tht doesn't work.

how to pull url and pass variable to python 3's http.server

My google-fu is failing me, perhaps because it is late.
Given the code below, I need to take everything after the domain.tld/ and parse it. It will then run against a database (in the example I'm using a dict, but in reality I'll be making a call to mysql, will that change it?)
Then, it will serve up a redirect header with that url.
from http.server import BaseHTTPRequestHandler, HTTPServer
class HTTPServer_RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(301)
self.send_header('Location', url)
self.end_headers()
return
array["stuff"] = "http://google.com"
array["thing"] = "http://yahoo.com"
url = array[page]
server_address = ('0.0.0.0', 80)
httpd = HTTPServer(server_address, HTTPServer_RequestHandler)
httpd.serve_forever()
It may be a bit late, but according to the documentation, self.path should return the url after the location of your server

Using stem to control Tor in python33

I am trying to use stem to have a small script run through Tor. I can't seem to get stem to work. Here is my code:
import urllib.request
import re
from stem.connection import connect_port
from stem import Signal
from stem.control import Controller
controller = connect_port(port=9151)
def change():
controller.authenticate()
controller.signal(Signal.NEWNYM)
def getIp():
print (urllib.request.urlopen("http://my-ip.heroku.com").read(30).decode('utf-8'))
def connectTor():
controller = connect_port(port=9151)
controller.connect()
getIp()
if not controller:
sys.exit(1)
print("nope")
def disconnect():
controller.close()
if __name__ == '__main__':
connectTor()
getIP()
change()
getIp()
disconnect()
Basically, all of the IPs that display are the same, when in theory, they should all be different. What can I do to make this code work?
To use Tor you need to direct traffic through its SocksPort (Tor acts as a local socks proxy). In your code above you don't have anything attempting to make urllib go through Tor.
For examples see Stem's client usage tutorials. I'm not sure offhand if SocksiPy or PycURL have Python 3.x counterparts. If not then you'll need to find an alternative.

Resources