Tag Archives: Python

How to import posts from WordPress to Pelican blog


Pelican is a python powered static site generator which is perfect for creating open blog, project page etc. It is an opensource project, there are many useful plugins and themes to explore.

Compose post with markdown file and host your site with GitHub Page, that make simple.

Import WordPress Posts

You can download posts from WordPress and have it on your GitHub blog.

  • Download WordPress posts using WP Admin tools
  • fetch posts from posts.xml file using command line tool as follows
pelican-import -m markdown --wpfile wp/posts.xml

Here is a demo of GitHub Page made in Pelican

How to pass python list to JavaScript in Flask app


You can’t use Python list directly into JavaScript, JavaScript lislt/array is not compatible with Python or wise versa. So what to do.

Solution

I have a list of names, which I want pass to a JavaScript in a Flask ninja template. Ninja template allow use to safely convert the python list to Json string then we can pass it to the JavaScript function / just JavaScript

<script type="text/javascript">

        dn = {{ distabr|tojson }}
</script>

You can’t use same route variable in multiple places in same template, it may not serve the purpose

In JavaScript Functions

Suppose you have separate JavaScript function files for some functionality like drawing analytic plots and pie diagram, or some donut chart. So how do we pass value to those functions ?

You can create a JavaScript as above, in your current template, then in function create a script variable to use it as follows.

function init_echarts() {
    var distNames=dn;
}

That’s all you need to know to embed some morris diagram to your flask app.

You should look at Morris JS , it is free and easy to use JavaScript charts library.

Pass variables to other templates in Flask


Flask is one of my Python frame work in which I build simple web application with ease and peace. Today we learn how to pass a variables to other templates in a Flask application.

Suppose your web app have a base template and a top nav bar template which included using

{% include "site_template/top_navigation.html" %}

and you want to pass a title or something else from a Index page to navigation bar where you want show up some text.

Using {% set %} you can create global variables.

The solution

We can use a set block in top of the index page as follows ,to pass variables to other sub templates

{% set mytitle=title %}

In the route it will look like

return render_template('index.html',  title=title)

and in the nav bar page we can use as mytitle as variable using

<div id="site_title"><h2  >{{ mytitle}} </h2></div>

If you had doubt and suggestion please leave a comment

RapidAPI example using request in Python


This tutorial is similar to RapidAPI example found in the official blog, with one exception, this example is users request method instead of unirest package which is not available on RapidAPI blog.

RapidAPI

RapidAPI is a website which provides useful APIs (Application Programing Interface) like Yahoo Finance, Email Verification, Geolocation which can be used to add features to your websites and apps using variety of programming languages like Python, Java, .Net etc.

Yahoo Finance example

For creating application to show stock chart using YahooFinanceAPI and Python, we are go through the following

  • Create a Rapid API Account
  • Subscribe to Yahoo Finance to get the endpoint (Which is a URL for getting information)
  • Create methods to connect API and Process data
  • Draw Plot

Install requirements

Install required packages using pip. I suggest using Python virtual environment.

pip install seaborn pandas 

Complete Source code

import json
from datetime import datetime
import matplotlib.pyplot as plt
import pandas as pd
import requests
import seaborn as sns
from matplotlib import rcParams
from past.builtins import raw_input

RAPIDAPI_KEY = "<YOUR_RAPIDAPI_KEY>"
RAPIDAPI_HOST = "<YOUR_RAPIDAPI_ENDPOINT>"

symbol_string = ""
inputdata = {}


def fetchStockData(symbol):
    url = "https://apidojo-yahoo-finance-v1.p.rapidapi.com/market/get-charts"

    querystring = {"comparisons": "%5EGDAXI%2C%5EFCHI", "region": "US", "lang": "en", "symbol": symbol,
                   "interval": "5m", "range": "1d"}

    headers = {
        'x-rapidapi-host': "apidojo-yahoo-finance-v1.p.rapidapi.com",
        'x-rapidapi-key': "275d968795msheb0c2d90f2d7a32p1141eajsnef8c254e756a"
    }
    response = requests.request("GET", url, headers=headers, params=querystring)
    if (response.status_code == 200):

        return json.loads(response.text)
    else:
        return None


def parseTimestamp(inputdata):
    timestamplist = []
    timestamplist.extend(inputdata["chart"]["result"][0]["timestamp"])
    timestamplist.extend(inputdata["chart"]["result"][0]["timestamp"])
    calendertime = []
    for ts in timestamplist:
        dt = datetime.fromtimestamp(ts)
        calendertime.append(dt.strftime("%m/%d/%Y"))
    return calendertime


def parseValues(inputdata):
    valueList = []
    valueList.extend(inputdata["chart"]["result"][0]["indicators"]["quote"][0]["open"])
    valueList.extend(inputdata["chart"]["result"][0]["indicators"]["quote"][0]["close"])
    return valueList


def attachEvents(inputdata):
    eventlist = []
    for i in range(0, len(inputdata["chart"]["result"][0]["timestamp"])):
        eventlist.append("open")
    for i in range(0, len(inputdata["chart"]["result"][0]["timestamp"])):
        eventlist.append("close")
    return eventlist


if __name__ == "__main__":
    try:
        while len(symbol_string) <= 2:
            symbol_string = raw_input("Enter the stock symbol: ")
        retdata = fetchStockData(symbol_string)

        if (None != inputdata):
            inputdata["Timestamp"] = parseTimestamp(retdata)
            inputdata["Values"] = parseValues(retdata)
            inputdata["Events"] = attachEvents(retdata)
            df = pd.DataFrame(inputdata)
            sns.set(style="darkgrid")
            rcParams['figure.figsize'] = 13, 5
            rcParams['figure.subplot.bottom'] = 0.2

            ax = sns.lineplot(x="Timestamp", y="Values", hue="Events", dashes=False, markers=True,
                              data=df, sort=False)
            ax.set_title('Symbol: ' + symbol_string)

            plt.xticks(
                rotation=45,
                horizontalalignment='right',
                fontweight='light',
                fontsize='xx-small'
            )
            plt.show()
    except Exception as e:
        print("Error")
        print(e)

Output

Python Library Tips: timedelta


Timedelta

Timedelta class represent not any particular date or time, but it represents a span of time. This class will be helpful when you need to run some math on date and time. Say what will be this day on after few weeks or what will be this day in future year.

Following example will make it clear

from datetime import date
from datetime import timedelta

print(f'todays date {date.today()} after 1 year will be {date.today()+ timedelta(days=365)}')

Output 
todays date 2020-06-27 after 1 year will be 2021-06-27

Here I used the f.string to construct the message , the timedelta represent one year, 365 days. You can find what will be the date before few weeks back using date -timedelta(weeks=4)

Pyboard for covid-19 status


Pyboardc19 is my leisure time project, I was start working one week ago now it is hosted on Heroku.com.

The dashboard offer live update for all Indian state and for rest of the world in the upcoming updates.

This is a minimal Flask,Python project, all the data which is source of the report is coming from official IndianCovid19 API as json file.

I also used bootstrap template, morris chart morrischart library, echart for this project.

Pyboard app Python  project
iPyboard App

Please share and comment. The project will be soon available on my GitHub Profile, so that you can use it for create your own.

Thanks to awesome bootstrap template from Colorlib.

Escape: I want to include more countries to dashboard, if you don’t mind please share json API

Thank you

Python Library Tips: date formatting


Date formatting

In Python you can format date string using following predefined strings ,

%y/%Y –Year %a/A –Week Day %b/B –Month and %d for day

The letter with lowercase (%y/Y%) gives you abbreviated values, say 20 for 2020, Thu for Thursday etc

>>> print( today.strftime("%y %b %a"))
20 Jun Thu
>>> print( today.strftime("%a,%d,%B,%y "))
Thu,18,June,20 

Locale date

Some times your application may be consumed by people for different localities or people from different countries, of course the date and time will be different. Python allows you to format date and time according to locale settings.

>>> print(today.strftime("%c"))
Thu Jun 18 00:00:00 2020
>>> print(today.strftime("%x"))
06/18/20
>>> print(today.strftime("%X"))

Here %c stand for locale’s date and time , %x for locale’s time and %X for locale’s date

You can also use predefined string s for format time . %I/H for 12/24 Hour, %M for Minutes, %S for second and % p for locales’s AM/PM


Python Library Tips: today()


Today()

Today I want to look around Today function which provided by Standard Python Library. This function can offer much of today’s date. Let’s start with printing what’s today date

from datetime import date
today=date.today()
print(today)

today variable also holding today() properties such as day,year,month,weekday etc. You can use them as follows.

Photo by Pixabay on Pexels.com
print(today.weekday())

weekday gives you number representing week day from 0-6, Monday as first day. You can use the weekday for printing days in a week, Monday or Sunday as first day as follows

wdays=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
print('Today is %s ' %wdays[today.weekday()])

Python Library Tips: % formatting


% formatting

In Python you can format string in a variety of ways. Using the % symbol you can place string almost any where.

print('customer A bought %s Quantity of Goods at %s unit price' %(qty,price))

#Output

customer A bought 100 Quantity of Goods at 70 unit price

The conversion types are:

ConversionMeaningNotes
'd'Signed integer decimal.
'i'Signed integer decimal.
'o'Signed octal value.(1)
'u'Obsolete type – it is identical to 'd'.(6)
'x'Signed hexadecimal (lowercase).(2)
'X'Signed hexadecimal (uppercase).(2)
'e'Floating point exponential format (lowercase).(3)
'E'Floating point exponential format (uppercase).(3)
'f'Floating point decimal format.(3)
'F'Floating point decimal format.(3)
'g'Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.(4)
'G'Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.(4)
'c'Single character (accepts integer or single character string).
'r'String (converts any Python object using repr()).(5)
's'String (converts any Python object using str()).(5)
'a'String (converts any Python object using ascii()).(5)
'%'No argument is converted, results in a '%' character in the result.
Source : https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

Create Covid-19 data list using Python in 5 minute


This tutorial will tell how you can create a quick list of Covid-19 pandemic real time data list using simple Python Scrip.

For this we are using data API provided by CovidTracking.com. Our example relay on the JSON data file which offer an up to dated covid-19 data set.

Web Request and urllib2

First we need a web request and bring all the JSON object from the internet. Using urllib2 standard Python library we can fetch the web content as follows.

urldata = 'https://covidtracking.com/api/v1/states/current.json'
    weburl = urllib2.urlopen(urldata)
    print("result code :" + str(weburl.getcode()))
    if (weburl.getcode() == 200):
        data = weburl.read()
        printData(data)
    else:
        print "Some server related error occurs"
PYTHON SPIDER IDE