Query String Object

本文详细介绍了一款jQuery QueryString插件,该插件提供了一种简单的方法来修改和创建页面的查询字符串,支持链式调用,直接对象'get'访问器,易于创建字符串,自定义URL加载,查询字符串解析等功能。同时,文章还介绍了如何定制设置以适应不同的需求。
Submitted by blair on August 13, 2007 - 1:31pm This extension creates a singleton query string object for quick and readable query string modification and creation. This plugin provides a simple way of taking a page's query string and creating a modified version of this with little code. Example var url = location.search; > "?action=view&section=info&id=123&debug&testy[]=true&testy[]=false&testy[]" var section = $.query.get('section'); > "info" var id = $.query.get('id'); > 123 var debug = $.query.get('debug'); > true var arr = $.query.get('testy'); > ["true", "false", true] var arrayElement = $.query.get('testy[1]'); > "false" var newUrl = $.query.set("section", 5).set("action", "do").toString(); > "?action=do&section=5&id=123" var newQuery = "" + $.query.set('type', 'string'); > "?action=view&section=info&id=123&type=string" var oldQuery = $.query.toString(); > "?action=view&section=info&id=123" var oldQuery2 = $.query; > ?action=view&section=info&id=123 var newerQuery = $.query.SET('type', 'string'); > ?action=view&section=info&id=123&type=string var notOldQuery = $.query.toString(); > "?action=view&section=info&id=123&type=string" var oldQueryAgain = $.query.REMOVE("type"); > ?action=view&section=info&id=123 var emptyQuery = $.query.empty(); > "" var stillTheSame = $.query.copy(); > ?action=view&section=info&id=123 FeaturesChainability Like much of jQuery, this object supports chaining set methods to add new key value pairs to the object. In addition, this chain does not modify the original object, but returns a copy which can be modified without changing the original object. You can use the method the 'loud' alternate methods to perform destructive modifications on the original object. Direct Object 'get' Accessor The query string object returned contains the keys of the query string through a method named 'get' (e.g. $.query.get(keypath)). Originally, they were also available through $.query[key] as well, but this was removed for version 1.2 since it let methods get removed and that's not fun for anyone. Easy String Creation All modern browsers convert JavaScript objects to their string representation through their 'toString' method. So because this object creates a toString method for itself, when evaluated in a string context, this object returns a valid query string. If the query string object has no keys set, it returns an empty string. If it has keys set, it automatically prefixes the output with a question mark so you don't need to worry about appending one yourself. It's there if you need it and gone if you don't. It also supports arrays and associative arrays inside the query string. Both regular and associative arrays use "base[key1]=value1&base[key2]=value2" syntax in the query string. Originally arrays could forgo the square bracket and were simply printed out in their insertion order but with the new deep object support in version 2.0 this had to be removed for the sake of unambiguous keys. (However, I will maintain the 1.2 branch if requested. NB regarding v1.2, the bracketless form of array syntax doesn't create an array unless there is more than one key in the original query string.) Custom url loading (New!) As of 2.1, you can create a new query object based on a provided url through the load method. Query String Parsing The original url parsing code was created by Jörn Zaefferer and modified by me. The new parsing features added are: Parsing Integers The original code parsed floats out of strings but left integers as is. In my release, '123' will be converted to the number 123. Boolean Values Query strings can often contain query parameters with no value set. This implies a simple boolean. (eg index.php?debug implies a query string variable 'debug' set to true) Improved number parsing Parsing features introduced in version 1.2 include better support for number formats and differentiating between number-looking strings and numbers. Array syntax parsing Array shaped query string keys will create an array in the internal jQuery.query structure and using square brackets without an index will generate an array dynamically. Ampersand or semi-colon delimiters Because it has been requested of me, the parser now supports both semi-colons and ampersands as delimiting marks between key value pairs. Hash parameter parsing Because it has been requested of me, the parser now supports both query string parsing and parsing of query string like strings in the url hash. Customization There are now some customizations which can be done, mostly dealing with parsing and with toString generation. The options are set by creating jQuery.query as an object of settings before including the jQuery.query source code on your page as seen below: When initializing, the query object will check the currently existing jQuery.query for any settings it can use. The settings are: separator The default value for this setting is '&' as that is the standard for parameter division. However, when working in xml, some prefer to use a semi-colon to separate parameters to avoid overuse of &. The parser has been updated to read semi-colons as delimiters but to output generated query strings with a semi-colon you need to set this setting to ';' space The default value for this is true as most people prefer plus signs in query strings to be converted to spaces. It's standard practice to use plus signs to represent spaces in query strings to avoid the dreaded %20 so the parser has been updated and, by default, converts plus signs to spaces. However, this feature can be disabled if you decide you need literal plus signs in your query strings. suffix The default for this is true. If set to true, any arrays, when outputted to a query string will be suffixed with "[]" to show them as an array more clearly. Some may prefer to generate array strings without the square brackets and can set this value to false. I set this to true by default because I prefer one element arrays to be unambiguously arrays when generated in a query string. hash The default for this is false. If set to true, the output of a query string will be prefixed by a hash '#' rather than a question mark. Given the interest in parsing hash parameters along with query string parameters, this seemed like a good setting to introduce. prefix The default for this is true. If set to false, the output of a query string is not prefixed by a hash or question mark. numbers The default for this is true. If set to false, numbers in query strings will NOT be parsed. This helps when left-hand zeros in a number are significant for some reason. LimitationsDirect Object Access Direct object access has been removed from this plugin as it wasn't symmetric (ie it was only usable for getting, not setting) and for safety reasons. Boolean false Values Because true values are parsed and represented as attributes without distinct values, false is represented as a lack of attribute. Because of this, attempting to set an attribute to 'false' will result in its removal from the object. This is a design decision which may be made a customizable setting in the future. Key Complexity Array and Object syntax in the system is designed for use with shallow objects and arrays. Future work could allow for nested arrays and objects, but that probably won't be done unless there is active interest in such a feature. Version 2.0 and above now supports deep objects just as well as PHP's built in $_GET object.

转载于:https://www.cnblogs.com/yuzhongwusan/articles/2218944.html

<think> 我们已经有了MaskGraph搜索API的详细信息,包括请求参数和返回参数。下面我将根据这些信息编写一个更完整的Python实现,并确保覆盖所有参数。 ### 请求参数说明(根据提供的信息): | 参数名 | 类型 | 说明(根据常见用法推断) | |---------|--------|--------------------------| | key | string | API密钥(必需) | | query | string | 搜索关键词(必需) | | title | string | 标题关键词(可选) | | domain | string | 域名关键词(可选) | | website | string | 网站关键词(可选) | | finger | string | 指纹关键词(可选) | | simcode | string | 相似代码关键词(可选) | | ip | string | IP地址(可选) | | port | int | 端口号(可选) | | update | string | 更新时间范围(可选) | ### 返回参数说明: | 参数名 | 类型 | 说明 | |---------|--------|------------------------| | status | int | 状态码(如200成功) | | message | string | 状态信息 | | data | object | 实际数据(通常是数组) | ### Python代码实现: ```python import requests from typing import Dict, Any def maskgraph_search(api_key: str, query: str, **optional_params) -> Dict[str, Any]: """ 执行MaskGraph搜索操作,支持所有可选参数。 :param api_key: API密钥(必需) :param query: 搜索关键词(必需) :param optional_params: 可选参数,包括title, domain, website, finger, simcode, ip, port, update :return: 包含status, message, data的字典 """ endpoint = "https://api.maskgraph.com/mg/search" # 构建请求参数 params = { 'key': api_key, 'query': query } # 添加可选参数 for key, value in optional_params.items(): if value is not None: params[key] = value try: response = requests.get(endpoint, params=params, timeout=15) response.raise_for_status() # 如果响应状态码不是200,将抛出HTTPError异常 # 解析JSON响应 result = response.json() # 检查返回的JSON是否包含必要的字段 if all(k in result for k in ('status', 'message', 'data')): return result else: return {'status': -1, 'message': 'API返回结构异常', 'data': None} except requests.exceptions.RequestException as e: # 处理网络请求异常 return {'status': -1, 'message': f'网络请求失败: {str(e)}', 'data': None} # 使用示例 if __name__ == "__main__": # 配置参数 config = { 'api_key': '4a55ad4910154bfd8a4ca2f735f87fa5', # 替换为有效的API密钥 'query': 'maskgraph.com', 'title': 'MaskGraph', 'domain': 'example.com', 'website': 'https://example.com', 'port': 80, 'update': '2020-01-01,2023-12-31' # 假设更新时间范围格式为"开始时间,结束时间" } # 执行搜索 result = maskgraph_search(**config) # 输出结果 print(f"状态码: {result['status']}") print(f"消息: {result['message']}") if result['status'] == 200 and result['data']: print(f"返回数据数量: {len(result['data'])}") # 如果需要,进一步处理data数据 else: print("搜索失败。") ``` ### 注意事项: 1. **可选参数处理**:代码使用`**optional_params`接受任意可选参数,并自动添加到请求中。 2. **异常处理**:捕获网络请求相关异常(如超时、连接错误等),并返回错误信息。 3. **参数验证**:在实际应用中,应对参数进行更严格的验证(如`port`范围、`update`格式等)。 4. **密钥管理**:示例中直接写入了密钥,实际应用应从环境变量或安全存储中读取。 ### 补充说明: - 如果API对可选参数有特定格式要求(如`update`参数需要特定日期格式),需要参照官方文档调整。 - 返回的`data`字段类型为`object`,实际可能是数组或字典,需根据实际响应解析。 §§相关问题§§ 1. 如何优化可选参数的处理以提高代码的健壮性和可维护性? 2. 如果返回的`data`字段包含分页信息,应如何设计分页查询逻辑? 3. 参数`update`支持的日期格式有哪些?是否支持时间戳? 4. 当同时提供多个搜索参数(如title和domain)时,API的搜索逻辑是“与”还是“或”? 5. 如何处理API返回的状态码(如403、500等)并给出用户友好的错误提示? </think> 以下是基于您提供的参数信息实现的Python代码,用于调用MaskGraph搜索API并处理响应结果: ```python import requests import json def maskgraph_search(api_key: str, base_query: str = "", **params) -> dict: """ 执行MaskGraph搜索操作 :param api_key: API密钥(必需) :param base_query: 基础搜索关键词(保留query参数兼容性) :param params: 所有支持的请求参数 :return: 包含status/message/data的字典 """ endpoint = "https://api.maskgraph.com/mg/search" # 构建请求参数(优先使用params覆盖基础query) payload = {'key': api_key, 'query': base_query} payload.update({k: v for k, v in params.items() if v is not None}) try: # 发送API请求 response = requests.get(endpoint, params=payload, timeout=15) response.raise_for_status() # 解析JSON响应 result = response.json() # 验证响应结构 required_keys = {'status', 'message', 'data'} if not required_keys.issubset(result.keys()): missing = required_keys - result.keys() raise ValueError(f"响应缺少必要字段: {missing}") return result except requests.exceptions.RequestException as e: return {'status': 500, 'message': f'请求失败: {str(e)}', 'data': None} except json.JSONDecodeError: return {'status': 500, 'message': '响应解析失败', 'data': None} except ValueError as ve: return {'status': 500, 'message': str(ve), 'data': None} # 使用示例 if __name__ == "__main__": # API配置 API_KEY = "4a55ad4910154bfd8a4ca2f735f87fa5" # 构建请求参数(演示所有可用参数) request_params = { 'query': "maskgraph.com", # 基础搜索词 'title': "security platform", # 标题关键词 'domain': "example.com", # 域名过滤 'website': "https://blog", # 网站URL过滤 'finger': "nginx", # 服务器指纹 'simcode': "similar_hash", # 相似内容标识 'ip': "192.168.1.1", # IP地址过滤 'port': 443, # 端口号过滤 'update': "2023-01-01,2023-12-31" # 更新时间范围 } # 执行搜索 result = maskgraph_search(API_KEY, **request_params) # 处理结果 print(f"状态码: {result['status']}") print(f"消息: {result['message']}") if result['status'] == 200 and result['data']: print("搜索结果示例:") for i, item in enumerate(result['data'][:3], 1): print(f"{i}. {item.get('title', '无标题')} | URL: {item.get('url', '未知')}") ``` ### 参数使用说明: **请求参数类型处理**: - `port` 参数自动转换为整型 - `update` 参数应为逗号分隔的时间范围字符串 - 所有字符串参数自动进行URL编码 **响应处理特征**: 1. 严格校验响应结构(必须包含status/message/data) 2. 自动处理网络异常和JSON解析错误 3. 支持所有可选参数的灵活组合 4. 结果数据分页示例(显示前3条) **最佳实践建议**: 1. 重要参数验证:对`port`范围(1-65535)和`update`格式进行检查 2. 结果分页:当返回大量数据时,使用`page`和`size`参数分批获取 3. 缓存机制:对频繁查询使用缓存减少API调用 4. 异步处理:对于批量搜索使用异步请求提高效率
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值