How to upload a file in Zoho using python?

UploadFile API Method of Zoho CRM

Table of Contents

  • Purpose
  • Request URL
  • Request Parameters
  • Python Code to Upload a file to a record
  • Sample Response

Purpose

You can use this method to attach files to records.

Request URL

XML Format:
https://crm.zoho.com/crm/private/xml/Leads/uploadFile?authtoken=Auth Token&scope=crmapi&id=Record Id&content=File Input Stream

JSON Format:
https://crm.zoho.com/crm/private/json/Leads/uploadFile?authtoken=Auth Token&scope=crmapi&id=Record Id&content=File Input Stream

Request Parameters

Parameter Data Type Description
authtoken* String Encrypted alphanumeric string to authenticate your Zoho credentials.
scope* String Specify the value as crmapi
id* String Specify unique ID of the “record” or “note” to which the file has to be attached.
content FileInputStream Pass the File Input Stream of the file
attachmentUrl String Attach a URL to a record.

* – Mandatory parameter

Important Note:

  • The total file size should not exceed 20 MB.
  • Your program can request only up to 60 uploadFile calls per min. If API User requests more than 60 calls, system will block the API access for 5 min.
  • If the size exceeds 20 MB, you will receive the following error message: “File size should not exceed 20 MB“. This limit does not apply to URLs attached via attachmentUrl.
  • The attached file will be available under the Attachments section in the Record Details Page.
  • Files can be attached to records in all modules except Reports, Dashboards and Forecasts.
  • In the case of the parameter attachmentUrl, content is not required as the attachment is from a URL.
    Example for attachmentUrl: crm/private/xml/Leads/uploadFile?authtoken=*****&scope=crmapi&id=<entity_id>&attachmentUrl=<insert_ URL>

Python Code to Upload a file to a record

Here’s a simple script that you can use to upload a file in zoho using python.

Go to https://pypi.python.org/pypi/MultipartPostHandler2/0.1.5 and get the egg file and install it.

In the program, you need to specify values for the following:
  • Your Auth Token
  • The ID of the Record
  • The uploadFile Request URL in the format mentioned above
  • The File Path i.e the location of the File

Sample Response

 

How to write port-forwarding program using Twisted

Recently I was faced with an issue where a long running process is listening on loop back IP (127.0.0.1) on port 8080 on one of our servers and client programs on other machines are trying to access it on server’s local IP 10.91.20.66.  We ended up at this situation when we have updated server configuration and restarted the server program and forgot to change IP binding info in config file from loop back to local IP. Server got busy with it’s work, with lots of customer’s connections already, by the time we have discovered that some services of  server are not accessible to client programs on other machines. So, the dummy’s guide to fixing it by changing config and restarting the server program is not an option as we can’t risk to disconnect existing customers. So, hot patching is the only option until we can restart the program at next scheduled down time.

I could have fixed this in couple of ways either by adding few lines to iptables configuration or by writing simple socket program in python. The task is to forward data coming in on local IP port 8080 to loop back IP (127.0.0.1) port 8080 and send replies back to source address. Forwarding one socket data to other socket is pretty trivial using Python’s socket library and Twisted made it even more trivial, so I went with the following solution using Twisted.

That’s it. Now, all I needed to do is to run this program by the following command

This simple program is made possible by the heavy lifting done by twisted library. Interested folks can look under hood at twisted’s portforward.py module.

How to integrate Celery into Django project

What is Celery?

Celery is a distributed task queue that allows us to execute jobs in background. This article explains how to set up Celery with Django to perform a background task.

Advantages:

  • Large or small, Celery makes scheduling such periodic tasks easy.
  • You never want end users to have to wait unnecessarily for pages to load or actions to complete. If a long process is part of your application’s workflow, you can use Celery to execute that process in the background, as resources become available, so that your application can continue to respond to client requests.

Celery uses brokers to pass messages between a Django Project and the Celery workers. We will use Redis as the message broker.

Installation

Before diving into Celery, follow the below setup points

Create a new virtualenv ‘venv’ using following command:

To activate the environment use command:

Install django and create a django project ‘myproject’. Make sure to activate a virtualenv, create a requirements.txt file and run the migrations. Then fire up the server and navigate to http://localhost:8000/ in your browser. You should see the familiar “Congratulations on your first Django-powered page” text. When done, kill the sever.

Let’s install Celery:

Now we will integrate Celery into our Django project with the following steps:

Step 1:

Inside the myproject directory i.e beside your settings.py create a new file called celery.py and add the following code in that:

Let’s break down what happens in the first module, first we import absolute imports from the future, so that our celery.py module will not clash with the library:

Then we set the default DJANGO_SETTINGS_MODULE for the celery command-line program:

Specifying the settings here means the celery command line program will know where your Django project is. This statement must always appear before the app instance is created, which is what we do next:

This is your instance of the library, you can have many instances but there’s probably no reason for that when using Django.

We also add the Django settings module as a configuration source for Celery. This means that you don’t have to use multiple configuration files, and instead configure Celery directly from the Django settings.

You can pass the object directly here, but using a string is better since then the worker doesn’t have to serialize the object when using Windows or execv:

Next, a common practice for reusable apps is to define all tasks in a separate tasks.py module, and Celery does have a way to autodiscover these modules:

Step 2:

To ensure that the Celery app is loaded when Django starts, add the following code into the __init__.py file that sits next to your settings.py file:

Project layout should look like:

Step 3:

Celery uses “brokers” to pass messages between a Django Project and the Celery workers. In this article, we will use Redis as the message broker.

First, install Redis from the official download page and then turn to your terminal, in a new terminal window, fire up the server:

You can test that Redis is working properly by typing this into your terminal:

Redis should reply with PONG – try it!

Once Redis is up, add the following code to your settings.py file:

You also need to add Redis as a dependency in the Django Project:

Test that the Celery worker is ready to receive tasks:

Kill the process with CTRL-C. Now, test that the Celery task scheduler is ready for action:

That’s it! You can now use Celery with Django. For more information on setting up Celery with Django, please check out the official Celery documentation.

How to implement PayPal payment gateway

The PayPal REST APIs are supported in two environments. Use the Sandbox environment for testing purposes, then move to the live environment for production processing.

The following endpoints address are two environments:

A complete REST operation is formed by combining an HTTP method with the full URI to the resource you’re addressing. For example, here is the operation to create a new payment:

The PayPal REST sdk can be obtained through pip

OAuth Request / Response

Client Id and Secret Id can be obtained from the application created in the paypal account.

For the following each API call, you’ll need to set request headers, including the access token.

Creating a WebProfile:

name:

The name of the web experience profile which should be unique among the profiles for a given merchant.

presentation:

It contains the parameters for style and presentation.

input_fields:

Parameters for input fields customization:

  1. allow_note : It enables the buyer to enter a note to the merchant on the paypal page during checkout.

  2. no_shipping : Determines whether or not PayPal displays shipping address fields on the experience pages.

    • 0 – PayPal displays the shipping address on the PayPal pages.
    • 1 – PayPal does not display shipping address fields whatsoever.
    • 2 – If you do not pass the shipping address, PayPal obtains it from the buyer’s account profile.
  3. address_override : Determines if the PayPal pages should display the shipping address supplied in this call, rather than the shipping address on file with PayPal for this buyer.

    • 0 – PayPal pages should display the address on file
    • 1 – PayPal pages should display the addresses supplied in this call instead of the address from the buyer’s PayPal account.
flow_config:

Parameters for flow configuration

  1. landing_page_type : Type of PayPal page to be displayed when a user lands on the PayPal site for checkout.

    • Billing – The Non-PayPal account landing page is used
    • Login – The paypal account login page is used.

Creating a Payment:


 

intent:

Payment intent. Allowed values are:

  • “sale” – For immediate payment
  • “authorize” – To authorize a payment for capture later
  • “order” – To create an order
experience_profile_id:

Id that will be obtained from the response of web profile request

payer:

Source of the funds for this payment represented by a PayPal account or a credit card.

  • payment_method : Payment method used. Must be either credit_card or paypal.
  • funding_instruments : A list of funding instruments for the current payment
  • payer_info : Information related to the payer
  • status : Status of the payer’s PayPal account. VERIFIED or UNVERIFIED
transactions:

Transactional details including the amount and item details.

redirect_urls:

Set of redirect URLs you provide only for PayPal-based payments.

  • return_url : The payer is redirected to this URL after approving the payment.
  • cancel_url : The payer is redirected to this URL after canceling the payment.

Execute an approved PayPal payment:

Use this call to complete a PayPal payment that has been approved by the payer.

The payment_id and payer_id are passed in the return_url. Once the payment is executed,it returns an array of payment object.

In the response state of the payment is obtained as : created approved failed, canceled, expired or pending.

The transaction details in the response contains state of the sale which is obtained as: pending, completed, refunded or partially_refunded

If the payment state is approved and the sale state is completed, the payment is successfully executed.

How to blink browser tab

Have you ever wished to blink browser tab on certain activity to get user’s attention?

Here is a scenario: Suppose there is a chat application installed on your website. Now what if the user of your website has multiple tabs opened in his browser and there is an incoming message in your website? How will you make your user realize that there is an unread message? Of course you can play some music, but it has some limitations. For instance, user may be listening to some songs or speakers could be muted. If none of them is applicable then also he has to go through each and every single tab in his browser and find out the one which is playing that music.

Visual blinking is the best way to get user’s attention and the easiest way to achieve that is to keep blinking the title of your website until user returns.

Here’s a JavaScript function to do so:

Just execute the function like below and browser tab will start blinking:

How to implement Websocket server using Twisted.

HTTP is a request-response type one way protocol. For the web application where continuous data is to be send, websocket was introduced. Unlike HTTP, websocket provides full duplex communication. Websocket, which can be said as an upgraded version of HTTP, is standardized to be used over TCP like HTTP. In this article I will share my experience in implementing websocket with twisted, a framework of python for internet. If you are familiar with websocket, then you can skip to twisted.web or else below is a little introduction to websocket.

WebSocket

To initiate communication using websocket, a Handshake need to be done between client and server. This procedure is backward compatible to HTTP’s request – response structure. First the client sends a handshake request to the server which looks like:

Sending Upgrade header in request with value websocket will acknowledge server about websocket communication. Now if server supports websocket with specified sub-protocols (Sec-WebSocket-Protocol) and version (Sec-WebSocket-Version), it will send adequate response . Possible response could be:

In response, server will send 101 Switching Protocols code and Sec-WebSocket-Accept whose value is calculated using Sec-WebSocket-Key. you can find more information here. After a successful handshake, any of the peer can send data to each other which must be encoded in binary format described in websocket RFC. A high-level overview of the framing is given in the following figure.

Twisted.web

websocket using twisted wire diagramAs in normal twisted.web server , at TCP level, we have HTTPChannel class (a child class of T.I.protocol.Protocol) and server.Site class (which is the child class of T.I.protocol.ServerFactory). Also a Resource instance needs to be passed to server.site class, so that it can serve GET request.

Whenever a data is received, DataReceived method of HTTPChannel is invoked. Now if data starts with ‘GET’, allow the HTTPChannel handle it, which will invoke the render function of the root resource provided to Site class. Render will set 101 response code and will compute the websocket response key. During handshake do not send any raw data, because if handshake is successful this will be considered as framed binary data. Even if you want to send, frame it and send.

If data doesn’t start with ‘GET’, that means we can assume it is a binary encoded message. Now this message can be decoded using Frame.py, which is a very simple data framing module following WebSocket specification. Data send to the client by server should be unmasked as per the websocket specification.

Below is code example of an echo websocket server.

 


How to install Asterisk on CentOS

In this installment of our How To, we are going to go over on the topic of how to install Asterisk on CentOS. For this we are going to use Asterisk 13 and CentOS 7 minimal version. But, instructions will mostly be similar to other versions of Asterisk and CentOS.

As a first step you need to download latest asterisk on to your machine. For this you need wget tool. As we are using minimal flavor of CentOS even wget tool is not available on fresh install. Run the following command to install wget.

Once, wget is installed successfully, run the following command to download asterisk.

Extract downloaded asterisk tar ball

Install the following dependencies

Once, all the above dependencies are installed. You can now run the following command to enable or disable modules of your choice.

After you are done with the menuselect screen, run the following command to compile and install asterisk

That’s it now you have asterisk installed successfully on your you machine. Run, the following command to start asterisk

Now, you should see asterisk console saying “Asterisk Ready”. Instead, if you encounter the following error

Don’t worry, just run the following command and start asterisk again after that.

 

How to install Asterisk 13 on Debian 8

In this post we are going to go over on how to install Asterisk 13 on Debian 8 from source. It’s pretty straight forward. Most of the commands shown below needs to be executed with root privileges. So, it’s better to login on console with root user account

First download latest Asterisk 13 version from Asterisk’s web site.

Extract downloaded tar ball

gcc comes installed on Debian 8. You need to install remaining dependencies using following commands

Once all the dependencies are installed. Run the following command

This is exit successfully without any errors. If there are any error like missing packages, you need to install them via apt-get. Before you compile Asterisk you have opportunity to enable or disable modules that you like by running following command

That command will bring up a console application as shown below, where you can navigate around using arrow keys of your keyboard and choose to enable or disable modules of your choice.

make-menuselect

Some of the modules in there depend on external packages. You need to install those dependencies in order enable those particular modules.

Now it’s time for compiling asterisk. Run the following command on console.

Once the above command runs with out error, you need to run the following command to install asterisk in system directories.

That’s it now you have asterisk installed on your machine. The following command should bring up asterisk console as shown below

asterisk-ready

Like it says Asterisk is now ready!