Skip to main content

4 posts tagged with "python"

View All Tags

· 3 min read

I've been gaming since 2003 till now.I remember those sleepless nights and how much fun i had playing PC games. I always wanted to be a game designer since my childhood days and have built lot of small games during my university days. After a very long time i invested some time and built a simple game using Python and Azure cosmosdb. I wanted to write how to build the game "Corona escape" with others in this blog post.

PreRequisities:

  • Python 3 Installed
  • VScode or Pycharm
  • Azure Subscription

Game Structure :

The coronavirus is fairly new that has taken the world by shock. It’s been two months since the outbreak started and it has shown that it isn’t as deadly as the SARS virus. This game "Corona Escape" is built using Pygame which is a library for beginners to cut their teeth on to get comfortable with learning programming and the process of game development and feel successful in making games. It's also a great rapid prototyping tool. This game is very similar to any jump game. The idea is that to escape from the virus as much as you can, user will be provided with a capsule to make the move fast and a mask to escape from the virus. I will not go in detail on the logic side of it as the source code is published here.

Corona Escape Game

Architecture below is fairly easy, its just a diagram with Cosmosdb to store the data and application insights to gather the user details (type of device,location etc). If you have plan to expand the game, you could add other components in the architecture such as azure functions etc.

Highest score is pushed to a text file and Azure cosmosdb for sharing the score across the users in the world. The related code resides in the cosmos.py which as follows,

def getLeaderBoard(self):
options = {}
options['enableCrossPartitionQuery'] = False
options['maxItemCount'] = 100
query = {'query': 'SELECT * FROM server s'}

results = self.client.QueryItems(self.container['_self'], query, options)

for result in results:
print(result['message'])


def pushData(self,username,highscore):
data = self.client.CreateItem(self.container['_self'], {
"username": str(username),
"highscore": str(highscore),
"message" : str(username) + " got " + str(highscore)
})


Make sure to create a cosmosdb account with the SQL API and pass those credentials under config.

self.config = {
'ENDPOINT': 'your endpoint',
'PRIMARYKEY': 'your cosmosdb primary key',
'DATABASE': 'your db',
'CONTAINER': 'your container'
}

How to run the Game:

  • Clone the repository from here
  • Make sure to install the dependencies using pip such as pygame
  • Run the game with the command python main.py

Hope this helps someone who want to build games using python and cosmosdb. Play the game and add your comments below. cheers!

· 3 min read

I've been gaming since 2003 till now.I remember those sleepless nights and how much fun i had playing PC games. I always wanted to be a game designer since my childhood days and have built lot of small games during my university days. After a very long time i invested some time and built a simple game using Python and Azure cosmosdb. I wanted to write how to build the game "Corona escape" with others in this blog post.

PreRequisities:

  • Python 3 Installed
  • VScode or Pycharm
  • Azure Subscription

Game Structure :

The coronavirus is fairly new that has taken the world by shock. It’s been two months since the outbreak started and it has shown that it isn’t as deadly as the SARS virus. This game "Corona Escape" is built using Pygame which is a library for beginners to cut their teeth on to get comfortable with learning programming and the process of game development and feel successful in making games. It's also a great rapid prototyping tool. This game is very similar to any jump game. The idea is that to escape from the virus as much as you can, user will be provided with a capsule to make the move fast and a mask to escape from the virus. I will not go in detail on the logic side of it as the source code is published here.

Corona Escape Game

Architecture below is fairly easy, its just a diagram with Cosmosdb to store the data and application insights to gather the user details (type of device,location etc). If you have plan to expand the game, you could add other components in the architecture such as azure functions etc.

Highest score is pushed to a text file and Azure cosmosdb for sharing the score across the users in the world. The related code resides in the cosmos.py which as follows,

def getLeaderBoard(self):
options = {}
options['enableCrossPartitionQuery'] = False
options['maxItemCount'] = 100
query = {'query': 'SELECT * FROM server s'}

results = self.client.QueryItems(self.container['_self'], query, options)

for result in results:
print(result['message'])


def pushData(self,username,highscore):
data = self.client.CreateItem(self.container['_self'], {
"username": str(username),
"highscore": str(highscore),
"message" : str(username) + " got " + str(highscore)
})


Make sure to create a cosmosdb account with the SQL API and pass those credentials under config.

self.config = {
'ENDPOINT': 'your endpoint',
'PRIMARYKEY': 'your cosmosdb primary key',
'DATABASE': 'your db',
'CONTAINER': 'your container'
}

How to run the Game:

  • Clone the repository from here
  • Make sure to install the dependencies using pip such as pygame
  • Run the game with the command python main.py

Hope this helps someone who want to build games using python and cosmosdb. Play the game and add your comments below. cheers!

· 4 min read

I have been using twitter for the past 10 years and it took nearly 5 years to get those 100 followers. I was not an active user till before 2 years. One great tip i learnt in recent times is that first thing you need to do is to get a really complete and professional profile. Most users look at profiles before following. Another best way is to increase followers on Twitter is being consistent with posting quality content. Automating your posts will help a lot with this. In this blog, i will explain how you could build a simple function and deploy it on Azure to increase your followers count and to be consistent with quality content.

PreRequisites:

Step 1 : Navigate to https://portal.azure.com/ and search for Function App in the search bar.

Step 2 : Create a Function app with the following settings, make sure you are setting the Consumption Plan and enable Application Insights.

Step 3 : Open Visual Studio Code(Make sure you have already installed the VSCode with the function core tools and extension). Select Ctrl + Shif + P to create a new Function Project and select the language as Python

Step 4 : Select the template as Timer trigger as we need to run every 15 minutes and you need to configure the cron expression (0 */15 * * * *) as well.

Give the function name as twitter_followers,

Step 5 : You will see the project template getting created. Next step is to edit the __init__.py, thats where you are going to add the logic. We will be using Tweepy library to get the data from twitter and to follow the person who is tweeting the tweet. The methods we will use in the function as retweet and create_friendship. Here is the whole logic of the function. As you can see any tweet that has the hashtag #azure will get retweeted and you will automatically follow the user who has tweeted the tweet.

import tweepy, time, datetime, logging, os
from datetime import date
import azure.functions as func
def main(mytimer: func.TimerRequest) -> None:
utc_timestamp = datetime.datetime.utcnow().replace(
tzinfo=datetime.timezone.utc).isoformat()
if mytimer.past_due:
logging.info('The timer is past due!')
logging.info('Python timer trigger function ran at %s', utc_timestamp)
auth = tweepy.OAuthHandler(os.environ["TWITTER_CONSUMER_KEY"], os.environ["TWITTER_CONSUMER_SECRET"])
auth.set_access_token(os.environ["TWITTER_ACCESS_TOKEN"], os.environ["TWITTER_ACCESS_TOKEN_SECRET"])
api = tweepy.API(auth)
today = str(date.today())
while True:
for tweet in tweepy.Cursor(api.search,q="#azure", lang="en", since=today).items(1):
try:
api.retweet(tweet.id)
except:
pass
try:
api.create_friendship(tweet.user.id)
except:
pass

Step 6: As you can see there are few environment variables which we are using in the code, we need to add those variables with the values in the local.settings.json file.

{  "IsEncrypted": false, 
"Values": {
"TWITTER_CONSUMER_KEY": "",
"TWITTER_CONSUMER_SECRET": "",
"TWITTER_ACCESS_TOKEN": "",
"TWITTER_ACCESS_TOKEN_SECRET": "",
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}

You need to get those keys from the twitter application you already created. if you dont have one, create from here.

Also you need to add the dependencies which are used in the above code inside the requirements.text file. dependencies.txt would have the following,

azure-functions
tweepy

Step 7 : Now we are done with everything, to publish the app to Azure, just press Ctrl+Shift+P and select Deploy to Funciton App

Step 8 : You can navigate to the function app on the Azure portal and make sure Application Insights is configured and as well as AppSettings are correct.

Make sure all the Environment variables are configured with the values.

Now you can start your function and navigate to Monitor section of the function app. You will see the real live telemetries from the app as follows,

All good, you can see the function running and you will see the tweets are automatically retweeted with the particular hasthage in your timeline and also you will see the number of followers increased. Happy Tweeting Folks!

You can get the sourcecode from here.

· 3 min read

There has been plenty of tutorials and blogs on how to configure webpy application with apache and mod_wsgi, but none of them turned into successful one. After 2 days of research i have found the solution and decided to write a blog on the same. Hope it will be useful for others.

In the future, I hope to update this post to also include a complete list of steps for getting setup with python’s webpy over lighttpd.

1. Install web.py

1.1. Install webpy with apt-get

sudo apt-get install python-webpy

1.2. Install webpy using easy_install using python setuptools 

1.2.1. Install python setuptools (easy_install)

# 1.2.1.1. Using apt-get:

sudo apt-get install python-setuptools
# 1.2.1.2. Manually retrieving easy_install from the web using wget

wget http://peak.telecommunity.com/dist/ez\_setup.py
sudo python ez_setup.py

# 1.2.2. Now get the web.py egg using python’s easy_install
# This will put the python ‘web’ module in your python environment path

sudo easy_install web.py

1.3. Install webpy straight from git

# Or, get webpy straight from git

git clone git://github.com/webpy/webpy.git ln -s `pwd`/webpy/web .

2. Write Your Web.py App
Choose a directory where you would like your web.py python application to live. If my username is ‘mek’ and I want to name my project ‘project’, I might make a directory /home/sajee/project.

2.1. Make a directory for your web.py app to live
# Replace the word project in the path below with your desired project name

mkdir ~/project
cd ~/project # move into the project directory you have created

2.2. Create your application file using web.py
# this will create our application file ~/project/main.py

touch main.py
2.3. Open your application with your favourite editor

# Substitute “emacs -nw” with an editor of your choice: vim, nano, etc

emacs -nw main.py

2.4. Paste the following in your app file and save

import os
import sys
import web

app_path = os.path.dirname(file)
sys.path.append(app_path)

if app_path: # Apache
os.chdir(app_path)
else: # CherryPy
app_path = os.getcwd()

urls = (
'/(.*)', 'hello'
)

**3\. Install Apache2**

3.1. Install apache and wsgi dependencies

sudo aptitude install apache2 apache2.2-common apache2-mpm-prefork apache2-utils libexpat1 ssl-cer
\# I like to also install python-dev (optional) to make sure I have
\# python’s latest support files

sudo apt-get install python-dev
3.2. Install apache mod\_wsgi and enable mod\_wsgi + mod\_rewrite

sudo aptitude install libapache2-mod-wsgi
sudo a2enmod mod-wsgi;sudo a2enmod rewrite
Need help troubleshooting your apache/mod\_wsgi installation?

**4\. Configure Apache2 With Your App**

In the following steps, replace ‘project’ with the name of your project

4.1. Make Apache Directories for your project

sudo mkdir /var/www/project
sudo mkdir /var/www/project/production
sudo mkdir /var/www/project/logs
sudo mkdir /var/www/project/public\_html
4.2. Create Symlinks
Creating symlinks to your project files is an important covention as, if there is a problem with one of your code bases, you can simply change your symlink to a stable codebase without having to modify your apache configuration.

ln -s ~/project/ production
ln -s ~/project/static public\_html # If you created the static directory in step 2.4.
4.3. Replace you /etc/apache2/sites-available/default with:



ServerAdmin [email protected] /var/www/project.com/public_html/ErrorLog /var/www/project.com/logs/error.logCustomLog /var/www/project.com/logs/access.log combinedWSGIScriptAlias / /var/www/project.com/production/main.pyAlias /static /var/www/project.com/public_htmlAddType text/html .pyWSGIDaemonProcess www-data threads=15WSGIProcessGroup www-dataOrder deny,allowAllow from allOptions +FollowSymLinksOptions -Indexes




4.4. Change the group and owner of files requiring write access to apache’s www-data
Careful in this step to only change the group and owner of directories or files that will require write access.

sudo chgrp -R www-data
sudo chown -R www-data

**5.Try to run!**

sudo /etc/init.d/apache2 restart # Open your browser and visit the url: http://localhost or 127.0.01

You will see Hello World on the browser.