首页 \ 问答 \ 将变量与不同的字符进行比较时避免重复变量(x == a或x == b或x == ...)[重复](Avoid repeating variable when comparing it to different characters (x == a or x == b or x==…) [duplicate])

将变量与不同的字符进行比较时避免重复变量(x == a或x == b或x == ...)[重复](Avoid repeating variable when comparing it to different characters (x == a or x == b or x==…) [duplicate])

这个问题在这里已有答案:

如下面的代码; 我该如何避免重复“char ==”?

for char in s:
    if char == 'a' or char == 'e' or char == 'i' or char == 'o' or char == 'u':
        do... 

是否有可能将第二行近似于用自然语言表达的内容:“如果char等于a,e,i,o或u ......”?


Like in the following code; how do I avoid repeating "char =="?

for char in s:
    if char == 'a' or char == 'e' or char == 'i' or char == 'o' or char == 'u':
        do... 

Is it possible to approximate the second line to what one would say in natural language: "if char is equal to a, e, i, o, or u..." ?


原文:https://stackoverflow.com/questions/40887836
更新时间:2023-05-28 20:05

最满意答案

实现此目的的一种简单方法是检查路由中传入请求的方案,例如:

(defroutes app-routes
  (POST "/route-one" request
        (if (= (:scheme req) :http)
          (process-requet request)
          {:status 403 :body "https not supported"}))
  (POST "/route-two" request
        (if (= (:scheme req) :https)
          (process-requet request)
          {:status 403 :body "http not supported"})))

你当然可以将这个方案检查提取到一个单独的函数或宏中,所以即使你有很多路由,那么这可能是一个可行的选择,而你的代码中没有太多的噪音。

如果您有许多路由,并且您不想为每个路由添加额外的呼叫或检查,那么实现此目的的另一种方法是向您的应用程序添加一些中间件。 中间件可以检查请求中包含的:scheme并拒绝不符合的请求。 例如:

(defn wrap-https-only [handler]
  (fn [req]
    (if (= (:scheme req) :https)
      (handler req)
      {:status 403 :body "http not supported"})))

(defn wrap-http-only [handler]
  (fn [req]
    (if (= (:scheme req) :http)
      (handler req)
      {:status 403 :body "https not supported"})))

棘手的部分是你想要有选择地将这个中间件应用于某些路由而不是其他路由,而Compojure并没有提供一种简单的方法来实现这一点。 如果您的所有http路由中都有一些共同的路径,以及所有的https路由(将它们分组),那么您可以使用如下模式:

(def http-routes
  (-> (routes (POST "/http-only/route-one" request
                    (process-requet request)))
      wrap-http-only))

(def https-routes
  (-> (routes (POST "/http-only/route-two" request
                    (process-requet request)))
      wrap-https-only))


(defroutes app-routes
  (ANY "/http-only/*" [] http-routes)
  (ANY "/https-only/*" [] https-routes))

您可以在此处看到中间件应用于每个路由子集,因此只有在路径的第一部分匹配时才会执行。 现在您可以添加任意数量的路由,中间件将负责所有这些路由的方案检查。 注意,这种方法要求您可以在初始的“app-routes”路由中以某种方式识别路由的子集,在这种情况下,我已经通过路径识别它们。

检查方案时需要注意的一点是:如果您决定将SSL卸载到负载均衡器,请注意这不会起作用。 在这种情况下,您的应用程序将始终收到HTTP(而非HTTPS)请求。 您通常可以通过简单地检查X-Forwarded-Proto标头而不是:scheme值来实现相同的目的。


One simple way to achieve this is to check the scheme of the incoming request inside your route, for example:

(defroutes app-routes
  (POST "/route-one" request
        (if (= (:scheme req) :http)
          (process-requet request)
          {:status 403 :body "https not supported"}))
  (POST "/route-two" request
        (if (= (:scheme req) :https)
          (process-requet request)
          {:status 403 :body "http not supported"})))

You can of course extract this scheme check into a separate function or macro, so even if you have many routes then this could be a viable option without too extra noise in your code.

If you have many routes, and you don't want to add an extra call or check to each, then another way to achieve this is to add some middleware to your application. Middleware can check the :scheme included in the request and reject requests that don't conform. For example:

(defn wrap-https-only [handler]
  (fn [req]
    (if (= (:scheme req) :https)
      (handler req)
      {:status 403 :body "http not supported"})))

(defn wrap-http-only [handler]
  (fn [req]
    (if (= (:scheme req) :http)
      (handler req)
      {:status 403 :body "https not supported"})))

The tricky part is that you want to selectively apply this middleware to some routes and not others, and Compojure does not offer a simple way to do this. If you have some common path in all your http routes, and all your https routes (to group them) then you can use a pattern like this:

(def http-routes
  (-> (routes (POST "/http-only/route-one" request
                    (process-requet request)))
      wrap-http-only))

(def https-routes
  (-> (routes (POST "/http-only/route-two" request
                    (process-requet request)))
      wrap-https-only))


(defroutes app-routes
  (ANY "/http-only/*" [] http-routes)
  (ANY "/https-only/*" [] https-routes))

You can see here that the middleware is applied to each subset of routes, and so it will only be executed if the first part of the path matches. Now you can add as many routes as you like, and the middleware will take care of the scheme check for all of them. Note, this approach requires that you can identify the subsets of routes in some way in the initial 'app-routes' routes, in this case I've identified them by the path.

One thing to note when checking the scheme: be warned that this wont work if you decide to offload SSL to a load balancer. In that case, your application will always receive HTTP (not HTTPS) requests. You can usually achieve the same by simply checking the X-Forwarded-Proto header instead of the :scheme value.

相关问答

更多
  • 您还可以考虑迁移到ring-logger ,其中包括编辑敏感信息的功能 : 默认情况下,ring-logger将编辑授权标头或任何名为password param(在任何嵌套级别)。 如果您希望ring-logger编辑其他参数,您可以配置redact-keys选项: (wrap-with-logger app {:redact-keys #{:senha :token}) Ring-logger将遍历params和headers并编辑任何在redact-keys集中找到其名称redact-keys ...
  • 您拥有的代码将可用,但您应该知道:reload-all只加载名称空间和名称空间依赖关系。 它不会递归加载这些名称空间的依赖关系。 我应该补充说,这种重新加载在生产系统中是不可强求的。 新部署的代码可能具有在系统重新启动之前不明显的错误(例如,它们依赖于仍然从正在运行的系统定义的var,但其声明已被删除)。 该系统将正常工作,但重启失败。 加载代码也会产生可能会影响生产环境的副作用。 尽管避免这些问题的风格很好,但真正确保意外事件不会发生的唯一方法是执行JVM重新启动。 在JVM上执行零宕机时间部署的最佳方式 ...
  • 实现此目的的一种简单方法是检查路由中传入请求的方案,例如: (defroutes app-routes (POST "/route-one" request (if (= (:scheme req) :http) (process-requet request) {:status 403 :body "https not supported"})) (POST "/route-two" request (if (= (:sche ...
  • 我认为这应该有效: (def header-buffer-size 1048576) (def config {:host "example.com" :port 8080 ; join? false ; and any other options... :configurator (fn [jetty] (doseq [connector (.getConnectors jetty)] (.setH ...
  • 总是只有一个顶级处理程序 - 毕竟,即使在某个概念级别有多个处理程序,应用程序需要决定以某种方式应用于给定请求的那个,因此做出选择的例程变为顶级处理程序。 所以,简短的回答是你需要提供一个函数来查看请求并将其交给应用程序内几个处理程序中的相应处理程序; 该函数是给run-jetty (或等价的)处理程序。 通常使用Ring + Compojure,您将拥有一些用于处理特定URI的基本(“内部”)处理程序和一些作为中间件实现的特殊用途处理程序(例如,用于404)。 前者倾向于以defroutes形式定义,而后 ...
  • Ring通过适配器与Web服务器配合使用。 最常见的情况是人们想要使用码头,所以Ring配有码头适配器 。 为了使用带有webbit的ring,你需要为它编写一个适配器。 不幸的是,似乎没有任何公共网页适配器已经存在,所以你可能不得不自己推出。 Ring works with web servers via adapters. The most common case is that people want to use jetty, so Ring ships with a jetty adapter. ...
  • 关于这个问题,Ring是错误的:ring不是http服务器,而是对http服务器的抽象。 环本身没有固定的线程模型:它真正关心的是你有一个从请求到响应的函数。 真正做出这个决定的是你使用的是哪个环形适配器。 到目前为止,最常见的是环形码头适配器,它是一个码头http处理程序,它通过环形委托给你的函数。 而且码头确实为每个请求设置了一个线程,这样就可以在一个线程中休眠而不会影响其他线程(但正如在另一个答案中指出的那样,线程不是免费的,因此您不需要定期执行大量的任务) 。 但是还有其他环线处理器具有不同的线程模 ...
  • 事实证明,我对配置文件的使用存在问题。 仔细看一下配置文件的收益率: 要激活除默认值之外的配置文件,请在前面加上+: $ lein with-profile +server run 因此,我不得不使用lein with-profile +prod ring uberjar 9696 (注意+ )。 It turns out that my use of the profile was problematic. A closer looks at the profile documentation yield ...
  • 我找到了如何解决这个问题,但没有令人满意的解释。 我使用wrap-json-response Ring中间件来获取HashMap并将其转换为JSON。 我转而使用json/write-str在我的处理程序中进行自己的转换,这就解决了这个问题。 猜测它可能与服务器处理输出缓冲有关,但这是猜测。 我已经梳理了Wireshark转储,我看不出两者之间有任何相关的差异。 发送的Content-Length字段完全相同。 '飞行中的字节'不同,分别为518和524。 不知道为什么网页浏览器对此感到满意,但Python ...
  • 如果您使用Cheshire生成JSON,您可以扩展其协议以处理序列化,然后它应该“正常工作”: (extend-protocol cheshire.generate/JSONable org.joda.time.DateTime (to-json [dt gen] (cheshire.generate/write-string gen (str dt)))) If you're using Cheshire to generate JSON, you can extend its prot ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)