how to have a single search API using path parameters (No form used)

2024/10/7 4:29:53

I have been using this view for searching a word as:

db refers mongo connection (just for ref)

@app.route('/')
def index():return render_template('index.html')@app.route('/words-<word>', methods=['GET', 'POST'])
def wordsearch(word):collection_name=word[0].lower()+'_collection'words=db[collection_name]data=words.find({'word':word})return render_template('wordsearch.html',data=data)

In index.html template I have been doing this to match this above url as:

    <script type="text/javascript">$(document).ready(function(){$('#submit').on('click', function() {var wordvalue = $("#word").val();  //getting word from element ID window.location.href ="/"+"words-"+wordvalue; //match the URL in view})});</script>

Does this can be done in more dynamic way ?, I mean this only works for word and not for other selections,or combination of selections as below:

The search input looks as:

word length: ()
word type  : ()
word       : ()submit

Now the API I have does match only if I send word , but how can I write a single API such that it should match all the possible combinations like word length + word type, word + word type (queries I would define on own)

What I have tried is :

@app.route('/<n>-letter-words', methods=['GET', 'POST'])
@app.route('/words-<word>', methods=['GET', 'POST'])
def wordsearch(word=None,n=None):if word:collection_name=word[0].lower()+'_collection'words=db[collection_name]data=words.find({'word':word})return render_template('wordsearch.html',data=data)data = 'you are searching with' + n + 'words'return render_template('lettersearch.html', data=data)

and in templates the scriptas:

    <script type="text/javascript">$(document).ready(function(){$('#submit').on('click', function() {var lettervalue = $("#wordlength").val();var wordvalue = $("#word").val();if (lettervalue==''){window.location.href ="/"+"words-"+wordvalue;}else{window.location.href ="/"+lettervalue+"-letter-words";}})});</script>

But confused if there are combination's like, 6-letter-words-of-verbs verb is a word type here

Also how to match the same URL for these combination's from template as i was doing with JQuery used in script above?

Is this the correct way? , I guess writing all possible routes in views and match it from template with the conditions in Jquery is a bad idea ,

any help/guiding links are appreciated ,TIA

Answer

Based on my comment-suggested recommendation to not ignore the behavior of the client browser, and to follow the intent of the definition of a URI (where /foo+bar and /bar+foo must not represent the same resource), the following is all you actually require, and handles URI-encoding of the values automatically, where your original did not handle URI encoding at all, and requires no additional client-side JavaScript of any kind:

<form action="/search"><input name="q"></form>

This is essentially how Google's (or DuckDuckGo's, or Yahoo!'s, or…) search form operates. Default method is GET (use a query string), input field given the abbreviated "field name" q (short for query). Using a tiny bit of JS one can bypass the form-encoding and apply the query directly as the "query string" — but remember to URI/URL-encode the value/query/search terms before combining! (And that doing this may bypass any "form data" collection performed by your backing web framework, e.g. you'll need to pull out request.query_string yourself.)

https://en.xdnf.cn/q/118861.html

Related Q&A

understanding the return type of anonymous function lambda

I am trying to understand how can lambda function be used. def adder_func(a, b):return a + bprint(adder_func(4, 5))# trying with lambda print(list(lambda a, b: a + b))When trying to use lambda as a add…

What is the meaning of Failed building wheel for flask-mysqldb in pip3 install?

I have a MacBook Air with macOs Sonoma 14.0 and when I write in the terminal $ pip3 install flask-mysqldbI get the error:How can I fix this?

How do I install pygame for a new version of idle? (Windows) [duplicate]

This question already has answers here:Error on install Pygame(3.9) install (Win10) [duplicate](1 answer)Unable to install pygame on Python via pip (Windows 10)(6 answers)Closed 3 years ago.I installed…

How to parse a dynamic dom element?

I want to make a parser for scraping price, however I cant find the working method of parsing innerHTMLI dont know why, but selenium (getAttribute(innerHTML)), phantomjs (page.evaluation function(){ret…

Get a string in Shell/Python with subprocess

After this topic Get a string in Shell/Python using sys.argv , I need to change my code, I need to use a subprocess in a main.py with this function :def download_several_apps(self):subproc_two = subpro…

Python Indentation Error when there is no indent error [duplicate]

This question already has answers here:Im getting an IndentationError (or a TabError). How do I fix it?(6 answers)Closed 7 months ago.Is it me or the interpreter? I see no indentation error in my cod…

How to mark rgb colors on a colorwheel in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 8 months ago.Improv…

Cant get Selenium to loop through two dialogue box options correctly

So basically: the goal is to click on each symbol for each sector on this website, that pops up a table with contact details, I want to copy all of that information and store it in a file. Right now ev…

Is it possible to use a JSON Web Token/JWT in a pip.conf file?

Im trying to make it possible for my application to fetch a package from a private feed in Azure DevOps using pip and a pip.conf file. I dont want to use a PAT for obvious reasons, so Ive created a ser…

sqlite3.Cursor object has no attribute __getitem__ Error in Python Flask

This is my code. I get this error everytime I press login:sqlite3.Cursor object has no attribute __getitem__This is my login tab:@app.route(/, methods=[GET, POST]) def login():error= Noneif request.met…