Home > OS >  Python3 Flask app - how to prevent hardcoding IPv4 address in Python and/or HTML?
Python3 Flask app - how to prevent hardcoding IPv4 address in Python and/or HTML?

Time:09-01

I am following this Network Chuck YT video to learn basic Python Flask. I got the app working, but I am running it inside an Ubuntu "multipass" VM, so it cannot use the loopback address, 127.0.0.1. When the app launches from the IPv4 address on port 8080 (currently 192.168.64.5) and it works fine on initial launch, but the IP of the Ubuntu VM can (and will) change, so I don't want to hardcode it, if possible.

Here is my Python Flask code:

#!/bin/python

from flask import Flask, render_template
import requests
import json

app = Flask(__name__)

def get_meme():
    sr = "/wholesomememes"
    url = "https://meme-api.herokuapp.com/gimme"   sr
    url = "https://meme-api.herokuapp.com/gimme"
    response = json.loads(requests.request("GET", url).text)
    meme_large = response["preview"][-2]
    subreddit = response["subreddit"]
    return meme_large, subreddit

@app.route("/")
def index():
    meme_pic,subreddit = get_meme()
    return render_template("meme_index.html", meme_pic=meme_pic, subreddit=subreddit)

app.run(host="192.168.64.5", port=8080)

Here is my HTML for the webpage:

<html>
<head>
<title>Meme Website</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="30;url=http://192.168.64.5:8080/" />
<style>
body {background-color:#000000;background-repeat:no-repeat;background-position:top-left}
h1 {text-align:center; font-family:Arial, sans-serif; color:#FFFFFF; background-color:#000000}
p {text-align:center;font-family:Georgia, serif; color:#FFFFFF; font-size:48px;font-style:normal}
</style>
</head>

<body>
<h1>A website to gather some memes!</h1>
<p>Here is your meme! This will refresh in 30 seconds!</p>
<p><img src="{{meme_pic}}"></p>
<p>Current subredddit: {{subreddit}} </p>
</body>
</html>

Is it possible to not hardcode the IPv4 address in either the Python Flask app or the HTML file?

UPDATE - final, fixed code here:

https://gitlab.com/kidacrimson/flask-memes

CodePudding user response:

Usually servers can use host="0.0.0.0" to accept clients from all Network Cards installed in computer - lan, wifi and loopback (127.0.0.1).

And pages can use urls like url=/ without http://192.168.64.5:8080

  • Related