0

I created a fairly simple Webapp using Flask. It calculates the current distance of all planets by using Skyfield.

The Server and the Python code work fine when i run them locally in my terminal. Unfortunately, when i deploy them to my Server with FastCGI, the site spits out totally different numbers whenever i hit refresh. I really can't find out what the problem is - can anyone help me?

Current Site: Click

The main Flask code:

#!/usr/bin/env python3.4 

from flask import Flask, render_template
import calculations

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("main.html", DistList=calculations.DistanceList(), DistRelList=calculations.DistanceRelationList())

@app.route("/sources")
def sources():
return render_template("sources.html")

if __name__=="__main__":
    app.run()

The python to calculate the distances:

import numpy
import time
from skyfield.api import load

ts = load.timescale()
planets = load('de421.bsp')

# create dictionary with all data needed. (body, min distance, max distance)
# Planetary Information taken from Nasa Fact Sheets 
# (https://nssdc.gsfc.nasa.gov/planetary/factsheet/)
celestialsDict = {
"Mercury": [planets["mercury"], 77342099, 221853642],
"Venus": [planets["venus"], 38297055, 260898687],
"Mars": [planets["mars"], 55650408, 401371087],
"Jupiter": [planets["JUPITER_BARYCENTER"], 588518023, 968047821],
"Saturn": [planets["SATURN_BARYCENTER"], 1195436585, 1658441995],
"Uranus": [planets["URANUS_BARYCENTER"], 2581909650, 3157263061],
"Neptune": [planets["NEPTUNE_BARYCENTER"], 4305875512, 4687350083],
"Pluto": [planets["PLUTO_BARYCENTER"], 4293758085, 7533299975],
"Moon": [planets["Moon"], 362102, 404694]
}

def DistanceToEarth(body):
    #return current distance to earth
    t = ts.now()
    astrometric = planets["earth"].at(t).observe(body)
    ra, dec, distance = astrometric.radec()
    return float("{:.2f}".format(distance.km))

def DistanceList():
    #returns a list of distances of the celestials
    DistList = []
    for body in celestialsDict:
        DistList.append(DistanceToEarth(celestialsDict[body][0]))
    return DistList

def DistanceRelation(body):
#returns the relative position in percent (0% = closes to earth, 100% = farthest from earth)
  relativePosition = ((DistanceToEarth(celestialsDict[body][0]) - celestialsDict[body][1]) / (celestialsDict[body][2] - celestialsDict[body][1])) * 100
  return relativePosition

def DistanceRelationList():
    DistRelList = []
    for body in celestialsDict:
        DistRelList.append(float("{:.2f}".format(DistanceRelation(body))))
    return DistRelList

And this is the FCGI-Script to start the server:

#!/usr/bin/env python3.4
RELATIVE_WEB_URL_PATH = '/Howfarismars/02_Layout/Code'
LOCAL_APPLICATION_PATH = os.path.expanduser('~') + '/html/Howfarismars/02_Layout/Code'

import sys
sys.path.insert(0, LOCAL_APPLICATION_PATH)

from flup.server.fcgi import WSGIServer
from app import app

class ScriptNamePatch(object):
  def __init__(self, app):
    self.app = app

  def __call__(self, environ, start_response):
    environ['SCRIPT_NAME'] = RELATIVE_WEB_URL_PATH
    return self.app(environ, start_response)

app = ScriptNamePatch(app)

if __name__ == '__main__':
  WSGIServer(app).run()
Savir
  • 17,568
  • 15
  • 82
  • 136
Monotom
  • 46
  • 5
  • 4
    What's the problem here? Planets move continuously, so surely it's expected that the distances should change? – Daniel Roseman Jan 04 '18 at 09:17
  • 1
    Are the numbers different, or just the same numbers but the order changes every time? – Chris Applegate Jan 04 '18 at 09:18
  • By looking at skyfield's [package description](https://pypi.python.org/pypi/skyfield) and seeing how it takes the current time into consideration, it looks like it's actually taking into consideration that planets do move. – Savir Jan 04 '18 at 09:19
  • To @DanielRoseman point. Earth moves at about 30kms per second around the sun. The changes I'm seeing for a refresh are less than 10km, so I'd argue you're seeing actual correct changes. – Horia Coman Jan 04 '18 at 09:20
  • 1
    You are right, the numbers are supposed to change, but they seem to get assigned to the wrong planets. e.g. The current distance of Pluto (362.492) is actually the current distance of moon. – Monotom Jan 04 '18 at 09:20
  • 1
    *they seem to get assigned to the wrong planets*: Without having any idea about... anything, really, I'd check the template: Make sure the values are properly sent to the HTML (put `prints()` around, for instance) – Savir Jan 04 '18 at 09:25
  • Thanks @BorrajaX! I checked the template again thoroughly and found out that the order of the Items in DistList, that is passed by Flask changes every time the server is restartet. I'm not sure why, though... is the order when iterating over a Dictionary guaranteed to be the same in python every time the function gets called? – Monotom Jan 04 '18 at 09:52
  • 2
    Dictionaries are unordered. – Daniel Jan 04 '18 at 09:54
  • @Daniel this could actually be my Problem here. Does this mean, that the for-loop in the DistanceList() function of my python-code produces a different List every time? – Monotom Jan 04 '18 at 09:56
  • 1
    *produces a different List every time?* --> Could be, yes. Check [collections.OrderedDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict) Or get the list of keys and sort them. Then use that sorted list to retrieve the dict's values – Savir Jan 04 '18 at 10:00
  • Thanks a lot @BorrajaX!! This worked. I changed the function to call an OrderedDict instead of a regular one and it now produces a list with Distances in the same order every time! I just had to rearrange the template HTML and it works fine now! – Monotom Jan 04 '18 at 10:20

0 Answers0