Showing posts with label tutorial. Show all posts
Showing posts with label tutorial. Show all posts
I wrote my previous article about python and python flask. It is needed for this tutorial. So if you are not followed it yet link is [1].
If you already familiar with python and if you already setup your machine for it no need of following it. As mentioned in the title I am going to show you how to implement simple SMS application within few minutes.
First of all it's better to download or clone the source code by using [2] URL.

Now you can see the project structure is same as my previous tutorial. So open the terminal in the location of above source code and type below command.
python app.py

Now server should start if you followed above steps correctly.
After this, You need to start IdeaMart simulator on your machine. Hope you already aware of it. If not you can go through my previous tutorial using [3] link.
After you run IdeaMart simulator using [4] URL, Open the SMS tab and add [5] to URL box in Application data.
Now it's time to test the application. You can send sms with your full name.
Ex - Tharinda Dilshan

Then the results should be appeared.

Now let's move into the implementation.

import logging
import urllib2

from flask import *

app = Flask(__name__)
app.debug = True


@app.route('/')
def hello_world():
    return render_template("index.html")


@app.route('/smsReceiver', methods=["GET", "POST"])
def sms_receiver():
    """
    This method is to retrieve request came from ideamart simulator of dialog and send sms message
    :return:
    """
    if request.method == "GET":
        response = make_response("Telco App is running")
        response.headers['Content-Type'] = 'application/json'
        response.headers['Accept'] = 'application/json'
        return response
    else:
        ideamart_message = json.loads(request.data)
        name = ideamart_message["message"].split(" ")[1]
        res = {'message': "Hi, " + name,
               "destinationAddresses": ideamart_message["sourceAddress"],
               "password": "password",  # This should be replaced with your ideamart app password
               "applicationId": ideamart_message["applicationId"]
               }

        # URL should be  changed to https://api.dialog.lk/sms/send when you host the application
        url = "http://localhost:7000/sms/send"
        req = urllib2.Request(url, data=json.dumps(res),
                              headers={"Content-Type": "application/json", "Accept": "application/json"})
        response = urllib2.urlopen(req)
        ideamart_respones = response.read()
        logging.error("Result content: " + ideamart_respones)

        if response.getcode() == 200:
            logging.info('*** Message delivered Successfully! ****')
            response = make_response("Message delivered Successfully!")
            response.headers['Content-Type'] = 'application/json'
            response.headers['Accept'] = 'application/json'
            return response
        else:
            logging.error(
                '*** Message was not delivered Successfully!! ERROR-CODE: ' + str(response.getcode()) + ' ****')
            response = make_response("Message was not delivered Successfully!")
            response.headers['Content-Type'] = 'application/json'
            response.headers['Accept'] = 'application/json'
            return response


if __name__ == '__main__':
    app.run(host="localhost", port=5000)


Above code is used to run the whole application. Basic functions related to flask framework is explained in my previous tutorial. Hope now you aware of it. When you click send button in ideamart simulator it will send a post request to the URL [5] that is mentioned above. As you can see in the program that request is handled by the function named as sms_receiver. The request message is taken as a variable called ideamart_message. After that, It is split into parts and send the response back to URL [6].

[6] URL should be changed when you host this application. The request should be send as a JSON request and headers should be added as you can see in the program. After sending the request, The response message which will be sent by the simulator can be seen as a log message in the running program console.

That's it! Hope this will help you.
Thanks for reading :)

If you have any problem, feel free to leave a comment and I appreciate any feedback.

For more info and to contact me go to my website.

[1] - https://tharindaehelepola.blogspot.com/2016/05/simple-web-application-using-python.html
[2] - https://github.com/tharinda221/ideamart-sms-application-python
[3] - https://tharindaehelepola.blogspot.com/2015/12/ideamart-simple-application-in-java.html
[4] - http://localhost:10001/
[5] - http://localhost:5000/smsReceiver
[6] - http://localhost:7000/sms/send

Python is awesome programming language. Anyone can learn it easily because its syntax is very simple. Because of that Most of scientist are choosing it for their researches. So that variety of packages available for different areas like image processing, machine learning, AI, etc. Building a web application using python is very import because above mentioned libraries are supported for python other than any other programming language.

In this tutorial I am going to show you how to build a simple web application using python. For that I am going to use flask as a web framework. The reason of using flask is it is easy to use and also it is a micro web framework with lot of features. In order to implement the application you should install python for your computer. I am going to use python 2.7 for this tutorial. For Ubuntu Machines python 2.7 is installed by default.

For windows machines,

Download python 2.7.11 using below link and install it to your computer.
https://www.python.org/ftp/python/2.7.10/python-2.7.10.msi

Then you have to configure the environment variables. If you are not aware of it, Use the below link.
http://www.computerhope.com/issues/ch000549.htm
You should add below line to the path variable.
C:\Python27\;C:\Python27\Scripts\        

Now have python on your computer. Then you have to install flask library to your computer. In order to do that you need to install python PIP to your machine.
For Linux users,
sudo apt-get -y install python-pip

For Windows users,
Go to the below link and select all the text in the page. Open the notepad and paste the text into it and save it as "get-pip.py".
https://bootstrap.pypa.io/get-pip.py
After that open the command prompt in the saved location and type,
python get-pip.py

Now you have python PIP on your computer. In order to install python-flask, Open the command prompt and type,
pip install flask

Now you have python flask on your computer. Now we can moving to the implementation part. I have implemented the application and you can clone it or download it using below link.
https://github.com/tharinda221/simple-flask-web-application
When you download the application exact it. Then open command prompt in the file location and type,
python simple-flask-web-application.py

If you followed above steps correctly below screen should be appeared.

According to the figure server is started at port 5000. If you type below URL on your favorite web browser index page will be appeared.


Now I am moving to the implementation. I have used Pycharm 2016 as a IDE. I recommended it if you are building complex applications in python. In the source code folder there is a file called simple-flask-web-application.py which is included all the implementation. I will go through its line by line.

from flask import *

app = Flask(__name__)


@app.route('/')
def hello_world():
    return render_template("index.html")


if __name__ == '__main__':
    app.run(host="localhost", port=5000)

In the first line flask library is imported. Then the second line is to initiate the application. That means create a Flask instance, in your main module. The idea of the first parameter is to give Flask an idea what belongs to your application. This name is used to find resources on the file system, can be used by extensions to improve debugging information and a lot more. The next line is connected a URL rule. Simply we can say when a request came to the "/" URL it will render "index.html" which is located in the template folder. The next line is to start the application. Host and port values are configured in the program itself. Hope you understand the tutorial. Likewise, We can create a web application using python flask in less amount of time and also you can create more advance applications using python.

IdeaMart

Ideamart is a platform presented by Dialog Axiata PLC to developers and content providers to use the Dialog network based features via shared APIs and monetize their efforts.

Hope you have an idea about what ideamart is. ideamart is a vast popular platform these days. I have seen lot of television advertisements also. But in the mean time I was unable to find any web application (website) which have  used ideamart APIs. So this tutorial will guide you how to use ideamart APIs in a web application. I am using basic java, JSP, servlet for this tutorial. You can extend it to any other framework like spring, vaadin, etc. This tutorial will guide you to implement following scenarios.
  • Receiving a message
  • Sending a message
  • Displaying received messages in a html page     
Prerequisites 
  • java 1.8
  • ideamart simulator 
  • apache tomcat 8
  • apache maven 3
  • IDE  (I am using intellij idea) 
Hope you are familiar with the above stuff. First you need to download or clone the repository. 
after downloading it you can open your favorite IDE and import the pom.xml file. It will download all the dependencies. To run the program you have to configure apache tomcat to your IDE 

How to configure apache tomcat in IntelliJ IDEA

Implementation 

Below image is displaying the source code structure after all the above configurations.
     
receive - This package is to handle the receiving messages. To receive a message and to send a message you need a library given by the ideamart. It is included in the resources directory. By implementing the MoSmsListener class you can handle the receiving messages. I hope you can easily understand it when you look at the Receive class implementation. receiving message URL is configured in the web.xml file. 

operations - when you receive a message you can do any operation for that. In this tutorial I am splitting it and put it into a hashmap. You can do any other operation you need.    

send - This package is to send messages to particular number. SmsRequestSender class can be used for that. 

db - This package is used for database operations. For this implementation i am using a hashmap. You can use any other database like sql or nosql. 

I hope you got some idea about the implementation. Now you are free to run the application. Before you run the program please make sure that all the libraries are included into the artifacts.
For that If you use intellij idea press Shift+ CTRL + ALT + S and then you can see the project structure.
It looks like below.
In the above picture both selected library and the other one are not in the artifacts. To add those into it right click on it and select "put into WEB-INF/lib" 
Then you can start the server and the ideamart simulator. 
You can see the index page and ideamart simulator like below.

                                                                                                             

URL - http://localhost:8080/Receiver
This URL is configured in the web.xml. In this tutorial I am going to get the name and the message with application name as a message. So your message format should have above three details.
ex - <app name> tharinda mymessage

Now you can send this message and wait for the response. When the response message came reload the index page and you will get the result below.
That's it! Hope this will help you. 

Thanks for reading :)

If you have any problem, feel free to leave a comment and I appreciate any feedback. 

For more info and contact me go to my website.

Spring can be used for pass objects through server to web page. In this article I am going to implement a HTML form as a data source. A java class can be created as a POJO(Plain Over Java Object) for assign the details of the input source. Form details can be assigned to a object and it can be passed to the another HTML page.

For the above task I used

1. Intellij idea
2. Java JDK 1.8
3. Maven 3.0

This Video will guide you how to create a simple application using spring MVC. Then you can gain some brief idea about how spring MVC works.

Here is the implementation for complete the above task.You can clone it or download it. You have to use a tomcat,glassfish or any other container for run this. Code included two main classes. greetMsgMoel class is act as a model and HelloControler  class is act as a controller. If you go through the implementation you can gain some idea about what's happening there. Both Home and simpleForm jsp files are handled by the controller. When you run the program it will scan the input and after you submit it the text you typed will display in another page.

I have used selenium web driver for testing.

" WebDriver is a tool for automating web application testing, and in particular to verify that they work as expected. It aims to provide a friendly API that's easy to explore and understand, easier to use than the Selenium-RC (1.0) API, which will help to make your tests easier to read and maintain."

This is what wiki says about WebDriver.
For further details here is the documentation of the selenium web driver.
http://www.seleniumhq.org/docs/03_webdriver.jsp

Here is the implementation for the above task. You can clone it or download it. First you need to run the spring application  which you have to test. Then you can add the localhost url to the testing implementation for testing. After that you have to run the testing implementation and it will open the firefox window and automatically go to the url of the web application. In the testing implementation I have added some test cases. So program will submit those test cases to the text box and then it will test if the submitted text is equal to the passed text.
If you need to gain some knowledge about spring MVC and selenium webDriver I hope this article can be useful to you.

Powered by Blogger.