Writing software is never easy. Writing software that appeals to users requires interacting with them.
So do you get relevant data that you can put to use on behalf of users? Python – the most-wanted language for building software according to the latest Stack Overflow survey – is here to help. In this post, we’ll show you how to use the Python input function, including how to get raw input from the keyboard.
What Is Python?
Python is a general purpose programming language that is widely used by both expert and beginning developers and is best known for its emphasis on readability. In fact, most Python functions and methods do exactly what they say.
Python code is at the root of many modern, cloud-hosted software applications. It’s also one of the most-used languages for developing data science algorithms. The Couchbase NoSQL database is built from the ground up to support Python, and if you’ve been working in the language for a while you may still need to upgrade from Python 2 to Python 3.
Fortunately, all of Python’s versions allow for capturing user input. Let’s review our options.
How to Use Python to Prompt for Input
If you’ve built an interactive application you’ll invariably want to prompt users to enter an integer or some other input, such as a name, title or topic.
Think of a standard contact page. Users who want to get in touch need a way to enter relevant information.
Python has two built-in functions for capturing user input:
input()
, which evaluates and converts Python input into a string format and then returns it to a variable that can be printed to screen as output.raw_input()
, which is the command in Python 2 for reading input exactly as it is typed on the keyboard, converting the results to a string to be returned to a variable.
As Python functions, input()
and raw_input()
follow the order of operations and pause the application until users complete the prompts. Use them to capture critical inputs only. Annoying users with prompts that feel optional could lead them to abandon your application instead of enduring the hassle.
Make Use of Python Input in Couchbase
Here’s how to leverage Python input to make a simple, interactive NoSQL document request application.
This example allows a user to enter a document ID, which then requests the document from Couchbase and then returns the results to the screen.
For the sake of this article, we’ll use Couchbase Server in the runtime environment – try Couchbase Cloud for an easy way to get started.
Once you’ve set up Couchbase Server, install the Python libraries using the pip command:
1 |
pip install couchbase |
Your Python scripts will then include all the settings needed to connect, including hostname, bucket name, user and password. In this case, the script uses the travel-sample
sample data bucket and the main administrator user info. The database is running on localhost
.
In this example, the script will request the document ID and use it as part of the get
function to request a specific document. All this logic is part of a function:
1 2 3 4 5 6 |
def getdoc(): docid = input("Enter document ID: ") try: result = cb.get(docid).value for item in result: print(item+":",result[item]) |
The running script prompts the user for a response. In this example, we use the document named airline_10
and output to the console:
1 2 3 4 5 6 7 8 9 10 11 12 |
C:\code> python finddoc.py Enter document ID: airline_10 Document ID: airline_10 ------------------------ callsign: MILE-AIR country: United States iata: Q5 icao: MLA id: 10 name: 40-Mile Air type: airline |
You may notice the above output is a little fancier than the basic code sample. There’s more on this to come in the best practices section below.
Best Practices for Taking User Input
- Check the sanity of the input: Check to see if the input was empty, too short, too long or the wrong type of data. In the example, we don’t worry too much as the database itself will catch any errors for us.
- Capture errors: What happens when a user enters a value that causes the rest of the application to fail? Use the Python
try
andexcept
clauses to handle exceptions and return meaningful feedback to the user. For example, if the user enters a wrong document ID, these clauses let the user know the ID does not exist. If they also just type random garbage it will say that it is not a valid document ID either.
1234try: ...except exceptions.DocumentNotFoundException:print("Document not found: "+docid)pass - Format output for readability: If the application is going to output data, add spacing and some structure to make it less overwhelming for the user. The script below adds some tabs between the field name and values. It also limits the printed output to 50 characters.
12for item in result:print(item+":\t\t",str(result[item])[:50]) - Use loops to keep things interactive: Rather than having the user re-run the script over and over, add some logic that helps them try again. In this case, an infinite while loop is used, which continually calls the
getdoc()
function until the user presses CTRL+C. That function adds a new line to keep it readable and asks for input again.
12while 1:getdoc()
123456789101112Enter document ID: airline_10Document ID: airline_10------------------------callsign: MILE-AIRcountry: United Statesiata: QSicao: MLAid: 10name: 40-Mile Airtype: airlineEnter document ID:
Try the full code example below and do some searches for documents such as: airline_10
, landmark_10019
, or hotel_10025
to see how the formatting and interaction make it easier for the user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
from couchbase.cluster import Cluster, ClusterOptions, QueryOptions, PasswordAuthenticator from couchbase import exceptions CONNSTR = "couchbase://localhost" BUCKET = "travel-sample" authenticator = PasswordAuthenticator("Administrator", "Administrator") cluster = Cluster(CONNSTR, ClusterOptions(authenticator)) cb = cluster.bucket(BUCKET) # cb_coll = cb.collection("default") # CB 7+ with collections def getdoc(): docid = input("\nEnter document ID: ") try: result = cb.get(docid).value # result = cb_coll.get(docid).value # CB 7+ with collections print("Document ID: "+docid) print("-------------------------") for item in result: print(item+":\t\t",str(result[item])[:50]) except exceptions.DocumentNotFoundException: print("Document no found: "+docid) pass while 1: getdoc() |
Conclusion
User input can be relatively easy to get when working in Python. We learned how to leverage the input()
and raw_input()
functions to bring data into Couchbase and better serve users. We also learned a handful of best practices and what to avoid when building interactive cloud software.
Python is already one of the most popular and desired languages for developing modern, cloud-hosted software. Learning how to leverage Python for your own work can be good for your career. Python’s straightforward development approach can also be good for your business.
Are you ready to take the next step in your enterprise cloud computing journey? Get started with a free trial of Couchbase today.